5

I would like to display a row of tow divs next to each other while in the next row, the next div sits directly under the last one. Like this:

enter image description here

Because the layout has to be built into an CMS, I can't put Box 1,3 and 2,4 in a separat div. Is there a way to achieve this kind of behavior without extra wrapping elements? (Normal float behavior doesn't work, display inline/inline-block also doesn't do the trick.) Or is some JavaScript required to build a layout like this?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
wowpatrick
  • 5,082
  • 15
  • 55
  • 86

2 Answers2

7

Because of the different heights, this looks like the problem where I still haven't found a general purpose pure CSS technique to handle it properly, despite trying really hard.

I've posted this answer before: css alignment question

I've given up and used a jQuery plugin to do this in the past for something similar:

jQuery Masonry

A picture is worth a thousand words:

enter image description here

Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349
6

you can use the nth-child(odd) to clear the float:left;.

css

.box {height:100px;width:100px;float:left;}
.box:nth-child(odd) {clear:left;}
.green {background:green;}
.red{background:red;}
.blue {background:blue;}
.yellow {background:yellow;}

html

<div class="box green">BOX 1</div>
<div class="box red">BOX 2</div>
<div class="box blue">BOX 3</div>
<div class="box yellow">BOX 4</div>

Demo: http://jsfiddle.net/YSP2S/

Keep in mind that this will not work for internet explorer. You can use conditional comment and javascript to achieve the same for internet explorer also.

Sotiris
  • 38,986
  • 11
  • 53
  • 85
  • 1
    +1, works fine, so long as his heights *are not* different (like they are in his picture). – thirtydot Feb 24 '11 at 15:33
  • @thirtydot you are right. Hm, otherwise I don't think to exist any pure css solution, only a javascript like this you suggested. – Sotiris Feb 24 '11 at 15:47
  • The problem is that the heights of the boxes _are_ different, because they are post previews with text, and the text always differs in lenght, so looks like I'll have to use JavaScrip/jQuery as thirtydot suggested ... But still helpful, thanks! And I also haven't seen jsfiddle.net until now, looks great for sharing code examples! – wowpatrick Feb 24 '11 at 16:04