Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

How can I wrap div elements that are different heights?

Olivia Rhye

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:

1  

‍

2

 

3

 

4

 

5

 

6

‍

.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:

‍

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy