自动定位div并排

时间:2012-06-24 23:50:29

标签: html css

我有一些自动生成的HTML代码。

当我在共享类上添加float:left;时,它看起来像这样:

+----------------+   +--------------+
|   div 1        |   |   div 2      |
|                |   |              |
|                |   +--------------+
|                |                  
|                |   +--------------+
|                |   |   div 3      |
+----------------+   +--------------+

我想要的是这个:

+----------------+   +--------------+
|   div 1        |   |   div 2      |
|                |   |              |
|                |   +--------------+
|                |                  
|                |   
|                |   
+----------------+   

+--------------+
|   div 3      |
+--------------+

我怎样才能得到这个结果?

我的CSS代码如下所示:

position: relative;
width: 40%;
float: left;
border: 1px solid black;
clear: left;

3 个答案:

答案 0 :(得分:1)

只需将clear: left;添加到div 3

即可

编辑:只需使用:nth-child(2n+1):nth-of-type(2n+1) css3选择器

答案 1 :(得分:1)

假设您的div有一个共同的类名,例如.boxes,请添加此CSS:

.boxes:nth-child(odd) {clear: left;}

这将使每个奇数编号的框清除浮动并开始一个新行。

或者,设置容器的宽度,使得只有两个框并排放置,然后使用display: inline-block代替float: left;

答案 2 :(得分:0)

添加一个CSS属性为clear的元素:both;在第二次DIV之后,类似于:

<div id="first"></div>
<div id="second"></div>
<br class="clear_both" />
<div id="third"></div>

然后在CSS中:

.clear_both {
    clear:both;
    height:0;
    width:0;
}