2010-04-12 67 views
6

這段代碼有什麼問題?浮動div後面不顯示

當我將float: left添加到#text#text2時,背景消失在div後面。但是,當我刪除float: left,一切看起來不錯。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
      "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<style type="text/css"> 
#first{ 
width: 200px; 
background-color: #345752; 
} 
#left_b{ 
background:transparent url('img/left.png'); 
background-position: left top; 
background-repeat: repeat-y; 
    min-height: 30px; 
} 
#right_b{ 
background:transparent url('img/right.png'); 
background-position: right top; 
background-repeat: repeat-y; 
} 
#text{ 
float: left; 
width: 50px; 
height: 30px; 
} 
#text2{ 
float: left; 
width: 70px; 
height: 30px; 
} 
</style> 
</head> 
<body> 
<div id = "first"> 
    <div id = "left_b"> 
     <div id = "right_b"> 
     <div id = "text">text 1</div> 
     <div id = "text2">text 2</div> 
     </div> 
    </div> 
</div> 
</body> 
</html> 

回答

8

您的容器分區#right_b正在崩潰,因爲它的子項是浮動的。您可以使用「清除修復」技術解決此問題。你可能想看看下面的堆棧溢出後的幾個解決方案:

一種流行的解決方案是增加overflow: hidden到您的div容器:#right_b

#right_b { 
    background:transparent url('img/right.png'); 
    background-position: right top; 
    background-repeat: repeat-y; 
    overflow: hidden; 
} 

另一個常見的問題是在關閉您的容器div之前添加<div style="clear: both;">&nbsp;</div>

<div id="first"> 
    <div id="left_b"> 
     <div id="right_b"> 
     <div id="text">text 1</div> 
     <div id="text2">text 2</div> 
     <div style="clear: both;">&nbsp;</div> 
     </div> 
    </div> 
</div> 
0

我認爲你必須給#right_b也最小高度:

#right_b{ 
background:transparent url('img/right.png'); 
background-position: right top; 
background-repeat: repeat-y; 
min-height: 30px; 
} 

浮動元素被拿出正常的文檔流,所以如果一個元素不包含其他「正常」的元素,該元素高度爲0(因爲它沒有內容)。

0

添加到您的樣式表:

.group:before, 
.group:after { 
    content:""; 
    display:table; 
} 
.group:after { 
    clear:both; 
} 
.group { 
    zoom:1; /* For IE 6/7 (trigger hasLayout) */ 
} 

而且 「羣體」 添加到你的 「right_b」 元素,這將解決倒塌的div:

<div id = "right_b" class="group"> 
    <div id = "text">text 1</div> 
    <div id = "text2">text 2</div> 
    </div>