2010-08-04 85 views
0

我要居中的div,像這樣:左側浮動的中央divs?

<div style='width:100%;'> 

    <div style='float:left; width=40px; height=40px;'></div> 
    <div style='float:left; width=40px; height=40px;'></div> 
    <div style='float:left; width=40px; height=40px;'></div> 
    ... 

</div> 

雖然我希望孩子的div將漂浮,於是他們出現在同一行,我想他們的水平行內居中。隨着更多的div被添加,他們可能需要最終包裝到另一行,這很好。但我希望這些項目也要集中。喜歡的東西:

|     | 
| X X X X X X | 
|  X X  | 

所以在上面,足夠孩子的div中添加的第一行是完全充滿,那麼這兩個額外的人換到另一條線路,但得到集中自己太。

什麼是正確的風格適用於此?

由於

+0

'顯示:內聯block'彈簧頭腦,但我不確定在這種情況下集中如何工作。 – You 2010-08-04 20:02:06

+1

對於初學者,您應該使用雙引號而不是單引號來分隔HTML屬性值。你的內聯樣式使用'='而不是':'... – 2010-08-04 20:03:06

回答

1

嘗試設置頂部DIV(具有寬度:100%)爲具有文本對齊:中心;然後給每個div一個顯示:inline-block;和margin:auto;

這將工作在鉻,歌劇,FF但不是資源管理器。

IE只支持inline-block的內聯項目,因此使它在IE工作使內部的div跨度,

這樣

<div style="width:100%;text-align:center;"> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
    <span style="margin:auto;background-color:red;width:100px;height:50px;display:inline-block;margin-bottom:5px;">&nbsp;</span> 
</div>