2012-06-24 106 views
0

我有一些自動生成的HTML代碼。自動排列div並排

當我的共享類添加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; 

回答

1

假設您的div有一個共同的類名,如.boxes,添加此CSS:

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

這將使每個奇數盒子清除浮子並開始新的一行。

或者,設置容器的寬度,使得只有兩個盒子可以並排放置,然後使用display: inline-block而不是float: left;

+0

他需要每一個**奇**一個清除,所以':nth-​​child(odd)' –

+0

最糟糕的是,我最初鍵入'2n + 1'之前,我想起了「奇數/偶數」關鍵字。 –

+0

我去顯示:inline-block;由於最小代碼^^ –

1

只需添加clear: left;到div 3

編輯:只需使用:nth-child(2n+1):nth-of-type(2n+1) CSS3選擇

+0

問題是可以生成三個以上的div。我希望他們在兩個人的對方 –

+1

@MichaelTotKorsgaard - 爲你更新答案:http://www.w3.org/TR/selectors/#structural-pseudos –

0

添加元素與clear屬性的CSS屬性: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; 
} 
+0

他的html是自動生成的,他不能添加元素... –