6

Say I have the following <ul> for use in a responsive design:

li {
  display: inline;
  padding-right: 1em;
}
<ul>
  <li>
    MenuItemHeinz
  </li>
  <li>
    MenuItemHinrich
  </li>
  <li>
    MenuItemRoffen
  </li>
  <li>
    MenuItemStaffRoffeltack
  </li>
  <li>
    MenuItemHeinz
  </li>
</ul>

When I resize the browser window or look at the page in a phone it breaks like this:

enter image description here

How can I make the menu items instead line up nicely on a grid when they break, for example like this? Preferably only using css ... of course ;)

enter image description here

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
PetaspeedBeaver
  • 433
  • 6
  • 17

2 Answers2

8

This layout is relatively simple with CSS flexbox.

ul {
  display: flex;
  flex-wrap: wrap;
  list-style-type: none;
  padding-left: 0;
}

ul li {
  flex: 0 0 calc(50% - 10px);
  margin: 5px;
  padding: 5px 0;
  text-align: center;
  box-sizing: border-box;
  border: 1px dashed red;
  background-color: yellow;
}
<ul>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
  <li><a href="#">item</a></li>
</ul>

jsFiddle demo

Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

You could use css columns and a media query.

li {
  display: inline;
  padding-right: 1em;
}
@media(max-width: 680px) {
  ul {
    -webkit-column-count: 2;
    -moz-column-count: 2;
    column-count: 2;
  }
  li {
    display:block;
  }
}
<ul>
  <li>
    MenuItemHeinz
  </li>
  <li>
    MenuItemHinrich
  </li>
  <li>
    MenuItemRoffen
  </li>
  <li>
    MenuItemStaffRoffeltack
  </li>
  <li>
    MenuItemHeinz
  </li>
</ul>
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • Super answer, and I already deployed it. But I was hoping to find a way to make the list still go left to right, **across the columns**, not up and down the rows. – PetaspeedBeaver Dec 17 '15 at 19:46