Position floated elements directly under each other [duplicate]

半城伤御伤魂 提交于 2019-11-28 04:27:08

问题


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.



来源:https://stackoverflow.com/questions/5106578/position-floated-elements-directly-under-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!