Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make list items line up on a grid when wrapping?

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

like image 536
PetaspeedBeaver Avatar asked Dec 16 '15 01:12

PetaspeedBeaver


2 Answers

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.

like image 73
Michael Benjamin Avatar answered Sep 28 '22 02:09

Michael Benjamin


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>
like image 35
Joseph Marikle Avatar answered Sep 28 '22 00:09

Joseph Marikle