Search code examples
htmlcssflexbox

Equal height rows in a flex container


As you can see, the list-items in the first row have same height. But items in the second row have different heights. I want all items to have a uniform height.

Is there any way to achieve this without giving fixed-height and only using flexbox?

enter image description here

Here is my code

.list {
  display: flex;
  flex-wrap: wrap;
  max-width: 500px;
}
.list-item {
  background-color: #ccc;
  display: flex;
  padding: 0.5em;
  width: 25%;
  margin-right: 1%;
  margin-bottom: 20px;
}
.list-content {
  width: 100%;
}
<ul class="list">
  <li class="list-item">
    <div class="list-content">
      <h2>box 1</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    </div>
  </li>
  <li class="list-item">
    <div class="list-content">
      <h3>box 2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    </div>
  </li>

  <li class="list-item">
    <div class="list-content">
      <h3>box 2</h3>
      <p>Lorem ipsum dolor</p>
    </div>
  </li>

  <li class="list-item">
    <div class="list-content">
      <h3>box 2</h3>
      <p>Lorem ipsum dolor</p>
    </div>
  </li>
  <li class="list-item">
    <div class="list-content">
      <h1>h1</h1>
    </div>
  </li>
</ul>


Solution

  • The answer is NO.

    The reason is provided in the flexbox specification:

    6. Flex Lines

    In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

    In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

    Equal height rows, however, are possible in CSS Grid Layout:

    Otherwise, consider a JavaScript alternative.