Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to float elements with different heights?

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?

like image 554
matt Avatar asked Aug 04 '12 20:08

matt


3 Answers

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

like image 161
Pevara Avatar answered Nov 13 '22 13:11

Pevara


As mentioned by @Arieljuod you can use display: inline-block instead of float. The beauty of this is that it will work in all browsers (including IE7+ with the hack below) and is completely fluid:

div {
    ...
    display: inline-block;
    vertical-align: top;
    margin-bottom: 0.3em;
    *display: inline;
    *margin-right: 0.3em;
    *zoom: 1;
    ...   
}

Working example: http://jsfiddle.net/cRKpD/1/

like image 45
My Head Hurts Avatar answered Nov 13 '22 12:11

My Head Hurts


I know I'm late to the party but someone just linked this question to another similar one and I realized this one misses the flexbox solution...
(which was not around when the question was asked).

Add the desired vendor prefixes and remove unnecessary in your CSS

.parent {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: -moz-box;
  display: flex;
  -webkit-flex-wrap: wrap;
      -ms-flex-wrap: wrap;
          flex-wrap: wrap;
  -webkit-flex-flow: row wrap;
      -ms-flex-flow: row wrap;
          flex-flow: row wrap;
}

example

like image 1
tao Avatar answered Nov 13 '22 12:11

tao