How to float elements with different heights?

matt picture matt · Aug 4, 2012 · Viewed 15k times · Source

I'm working on a responsive webdesign that floats multiple items in 4 columns side by side. Those items have different heights and hence floating doesn't properly work.

This is what happens at the moment:

floating wrong

Any ideas on how to make the elements float like that:

floating right

I guess this should work with jQuery "masonry", right? However I'm working with Zepto.js and I guess a jQuery plugin wouldn't work.

Is there any pure CSS (CSS3) way to that? Some trick or so?

If this wouldn't work with pure CSS or with JS is it possible to do this:

floating different

Now the second row with elements 5, 6 and 7 is not "really" floating the way you would expect it but there is a hidden line-break (clearfix) inside.

Is there any way to that with pure CSS? E.g. use nth-child(4n+4) and a pseudo-selector like :after to apply a line-break with content?

Any ideas on that? Any clever tricks to make that work?

Answer

Pevara picture Pevara · Aug 4, 2012

you could just apply a clear to every fifth element to force it to start all the way at the left. I think it would look something like this in css3:

div#wrapper > *:nth-child(4n+1) {
   clear: both;
}

jsFiddle demo