2011-12-05 146 views
10
<html> 
<head> 
<style type="text/css"> 
div 
{ 
background-color:#ccc; 
} 
</style> 
</head> 

<body> 
<div> 
<div style="float: left;">This is a text inside a div element.</div> 
<div style="float: right;">We are still in the div element.</div> 
</div> 

</body> 
</html> 

爲什麼在這兩個div之間不顯示背景顏色? Output after running this page帶子div的背景顏色

回答

7

當你浮動元素時,你應該提供浮動元素的寬度。否則,您可能會遇到不同瀏覽器的意外行爲。

Check this tutorial,有漂浮在CSS的很好的信息。 [鏈接已死]

基本上,如果你提供一個overflow:hidden;到容器div和提供寬度的浮動元素,你的問題將得到解決。

<div style="overflow: hidden;"> 
    <div style="float:left; width: 300px;">Some text</div> 
    <div style="float:right; width: 300px;">Some text</div> 
</div> 

同樣,無論你想正常化流量IKE可以添加另一個DIV這樣的:

<div> 
    <div style="float:left; width: 300px;">Some text</div> 
    <div style="float:right; width: 300px;">Some text</div> 
    <div style="clear:both;"></div> 
    <div>This div will be at the same place 
     as if the previous elements are not floated</div> 
</div> 

雙方將工作:)

編輯

另一種方法,我在這幾天經常使用的是浮動第一個元素,並將margin-left設置爲以下元素。例如:

<div> 
    <div style="float: left; width: 300px;">Some text</div> 
    <div style="margin-left: 300px;">Some text</div> 
    <div style="clear: both;"></div> 
</div> 

該方法的優點是以下元素(在這種情況下的第二個div)不需要固定寬度。另外,你可以跳過第三格(clear: both;)。這是可選的。我只是添加它,以防浮動div的高度比第二個div長,因爲如果您不添加它,父div將始終獲得第二個div的高度。

6

只需將容器格設置爲overflow: hidden;即可。

如果將元素設置爲浮動,它們將不再處於文檔的正常'流'中。

div { background: #ccc; overflow: hidden; } 

而且你甚至沒有取得一個寫意圓;)

2

這是因爲無論是div s的浮動,從而含有div沒有高度。如果您要添加第三個孩子div這不是浮動,請給它一個高度0clear:both您應該看到背景顏色出現。

+0

Yuck!儘可能不要使用'clear:both'黑客。幾乎總是(/總是)更好的解決方案。 – PeeHaa

+0

我並不知道「overflow:hidden」技巧。 – Gareth

+0

看起來像你今天學到的東西:)爲了完成我的評論和教育你更多;)當你想使用CSS3(例如拖放陰影)時,注意使用'overflow:hidden;'黑客。幸運的是,我們也有一個解決方案:http://fordinteractive.com/2009/12/goodbye-overflow-clearing-hack/ – PeeHaa

3

浮動元素不會影響父級的大小,除非父級特別包含使用overflow樣式的子級。

您的外部div與子div具有相同的背景顏色,但父級的高度爲零,因此您不會看到其背景。

1

您顯示的空白區域是一個正文部分,您將背景顏色設置爲div,但不在正文中。這是身體部分是空的原因。

顏色你應該添加以下代碼空白部分:

<html> 
<head> 
    <style type="text/css"> 
div 
{ 
background-color:#ccc; 
} 
body{ 
background-color:#ccc; 
} 
</style> 
</head> 

<body> 
<div> 
<div style="float: left;">This is a text inside a div element.</div> 
<div style="float: right;">We are still in the div element.</div> 
</div> 

</body> 
</html> 

您可以通過改變車身造型的背景顏色改變身體的背景顏色。