Position floated elements directly under each othe

2019-01-26 14:13发布

问题:

This question already has an answer here:

  • CSS Floating Divs with different height are aligned with space between them 3 answers

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:

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?

回答1:

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:



回答2:

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.