Search code examples
htmlcssvertical-alignment

Inline-block elements of the same height in a few lines


Can I do all the blocks of the same height without JS and min-height (as a special case)? Blocks can be placed on multiple lines.

Example jsfiddle

Correct height

ul {
  font-size: 0;
  max-width: 300px;
  text-align: center;
}

li {
  vertical-align: top;
  display: inline-block;
  width: 30%;
  margin: 1%;
  background: grey;
  font-size: 12px;
}
<ul>
  <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
  <li>Lorem ipsum dolor sit amet.</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
  <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
</ul>


Solution

  • If flexbox is an option, then you can make ul a wrapping flexbox.

    How this works?

    1. display: flex creates a flexbox which has the property to distribute whitespace between its children in various ways.

    2. flex-wrap: wrap allows the lis to go to the next line depending on the content

    3. justify-content: center does horizontal centering.

    4. Vertically the lis have a property called align-items: stretch, which is the default - this allows the heights of the lis to be equal in a line.

    See demo below:

    ul {
      font-size: 0;
      max-width: 300px;
      text-align: center;
      display:flex;
      flex-wrap:wrap;
      justify-content:center;
    }
    
    li {
      vertical-align: top;
      display: inline-block;
      width: 30%;
      margin: 1%;
      background: grey;
      font-size: 12px;
    }
    <ul>
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
      <li>Lorem ipsum dolor sit amet.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
    </ul>