Fixing floated elements’ order using CSS

columns

There’s a common issue in CSS layout making where when you have an array of floated elements with different heights chances are that their order will fall apart, as browsers don’t clear them cleverly and they simply try to fill their parent’s gaps with as many items as possible, usually ending up looking pretty bad.

See a quick demonstration of what I mean. In case 1, we have a plain old standard grid of floated elements, all with variable and unknown heights. This is supposed to be a 3×3 grid of elements (for example, a list of products in a product listing page), but notice how item No. 4 creeps in between 1 and 5, instead of committing to the normal flow by appearing under No. 1.

I’m pretty sure everyone has bumped into this little problem a few times and usually the solution is to apply a height equalizer jQuery plugin of some sort (by the way if you are in need of such a plugin for any reason I can’t recommend matchHeight enough).

A CSS solution

The solution to this issue is strikingly simple. You only have to set clear: left on the first item of each row. For example, if you had 3 columns (3 items) in each row of your grid all you’d have to do is:

.item:nth-child(3n+1) { /* Target only the first element of each row, i.e. 1st, 5th, 9th etc elements of our grid */
  clear: left;
}

 

So, in the case of our demo (case 2), in which we’re using Bootstrap, we’d simply do:

/* .row-equal is an extra class in the .row parent
so that we can limit our clearing only to that specific
case */
.row-equal [class="col-xs-4"]:nth-child(3n+1) {
  clear: left;
}

Similarly, for a grid of 4 columns we’d do:

.row-equal [class="col-xs-3"]:nth-child(4n+1) {
  clear: left;
}

And that’s it! No need for jQuery. Let me know if you’ve ever bumped into this problem and how you solve it in the comments section.

Leave a Reply

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