How can I wrap div elements that are different heights?

Caleb Szydlo

Wrapping divs and other block level elements is pretty easy if they’re all a consistent height, we can just set a width and a float and we’re done.

However when we have elements whose heights are being set dynamically we can run into issues when one element gets ‘caught’ on a taller element in the row above. For example:

<div id="container">
  <div class="tile">1</div>
  <div class="tile tile--2x">2</div>
  <div class="tile">3</div>
  <div class="tile">4</div>
  <div class="tile">5</div>
  <div class="tile">6</div>
</div>
.tile {
  width: 25%;
  padding: 2%;
  margin: 0 2% 20px;
  float: left;
  height: 100px;
  color: #fff;
  background: #f87d33;
}
.tile:nth-of-type(2n) {
  background: #f05423;
}
.tile--2x {
  height: 120px;
}

Sticks us with this:

1
2
3
4
5
6

 

To fix this we can add ‘clear: left’ to the first element in each row. I could just add a class onto the 1st and 4th elements in the html, however I often work inside of a loop of some sort and I like my css to be extensible. So instead I’ll us the selector :nth-of-type() and a formula to target every 3rd div, starting with the first:

.tile:nth-of-type(3n - 2) {
  clear: left;
}
1
2
3
4
5
6

 

There we have it, just like the slogan of a Taco Bell Cruch Wrap Supreme circa 2005 we are ‘Good to Go’. One note about responsive development, when you want to switch the number of columns you’ll need to specify ‘clear: none;’ to avoid alignment issues. For more on :nth-of-type() and :nth-child() check out this article from css-tricks.

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *