2015-05-29 71 views
4

我有以下code,其中ab div塊分別在左側和右側。爲什麼我的div與我的代碼中的其他div重疊?

<!--HTML--> 
<div style="background-color:#125467" id="a">a</div> 
<div style="background-color:#AABBFF" id="b">b</div> 
<div style="background-color:#990033" id="c">c</div> 
<div style="background-color:#885544" id="d">d</div> 
<div style="background-color:#7799BB" id="e">e</div> 
<div style="background-color:#33FF88" id="f">f</div> 
<div style="background-color:brown" id="g">g</div> 
<div style="background-color:blue" id="h">h</div 

/*CSS*/ 
div { 
    width: 100px; 
    height: 100px; 
    color: white; 
    text-align: center; 
    font-size: 20px; 
} 
* { 
    border: 1px black dashed 
} 

#a { 
    float:left; 
} 

#b { 
    float:right; 
} 

的問題是,我不明白爲什麼d塊重疊c塊像下面的圖片: C block overlapped by d block

但其它組件通常去。我知道如果我加

#c { 
    clear: both; 
} 

一切都會好的。 enter image description here

但爲什麼沒有clear:both它的行爲是這樣的?

+0

整個問題是浮動對象不會添加到它們正確駐留的對象的高度。 https://css-tricks.com/the-how-and-why-of-clearing-floats/ – Lain

+0

爲什麼不添加塊d的類? – Alex

回答

4

實際上,d塊並不重疊c。 這是一個重疊的塊c。

發生這種情況是因爲a和b都是float'ed,瀏覽器看到它們的計算高度爲0px,這意味着c,d,e,f都向上移動頁面,並且因爲a首先出現在DOM中坐在c的頂部。

0

嘗試使集裝箱

Position:relative; 

和元件或在其內部

Position:absolute; 
3

這是因爲float: left屬性

默認顯示模式是block。因此,divs會在另一個之後排在新的一行。但由於您已將float: left設置爲#a。div取自正常流程,忽略#a位置相對於其他元素,因此它重疊。