2013-04-23 20 views
6

我飄紅的div上藍色的div像圖片 enter image description here資料覈實,高度和浮

<div class="blue"> 
    <div style="height: 40px; float: left"></div> 
    <div style="height: 40px; float: left"></div> 
    <div style="height: 40px; float: left"></div> 

    <div style="height: 40px; float: left"></div> 
    <div style="height: 40px; float: left"></div> 
    <div style="height: 40px; float: left"></div> 
</div> 

我想做的事情,那麼藍格有紅色的DIV的高度。當我刪除浮動它沒關係。

回答

3

您需要添加display:table-cell;或溢出:隱藏;到你的藍色格子。這會讓父母成爲孩子的高度。

Demo

這樣的:

.blue{ 
    overflow:hidden; 
    //or 
    //display:table-cell; 
} 

阿里納斯 - 你需要的div的寬度時,他們是浮動的。

你也可以選擇使你的div類藍色浮動。但是這可能會導致文檔中出現一些不需要的行爲(如果div不應該浮動)。

+0

爲什麼需要寬?你可以讓寬度取決於內容... – Pevara 2013-04-23 20:21:00

+0

@PeterVR但實際上並沒有內容要顯示,這只是爲了演示目的。 – RelevantUsername 2013-04-23 20:23:50

0

簡單地漂浮在藍色的div:

.blue{ 
    float: left; 
} 

然後它會擴展到承擔其子女的身高。

如果浮動不是選項,我會將display設置爲inline-block以使其行爲與浮動元素的行爲相同。

.blue{ 
    display: inline-block; 
} 

參考:https://developer.mozilla.org/en-US/docs/CSS/display

0

這是被稱爲 'clearfix' 問題很常見的問題。更多信息可(例如)在這裏找到:Div rendering incorrectly in Firefox

總之,你應該添加一個類.clearfix給你父(藍色)格,看起來是這樣的:

.clearfix { 
    *zoom: 1; 
} 
.clearfix:before, 
.clearfix:after { 
    display: table; 
    content: ""; 
    line-height: 0; 
    } 
&:after { 
    clear: both; 
} 

這一個是「借來的'從Twitter Bootsrap,那裏有很多選擇。爲什麼以及如何工作,我建議使用Google搜索'clearfix'。

注意,存在其他「修復」像inline blocks工作,加入overflow: hidden甚至顯示爲table-cell。儘管它們可能在某些情況下工作,但它們幾乎都有其他副作用,或者不能完全跨瀏覽器,因此應謹慎使用它們。

0

如果你需要的東西乾淨,更有活力,試試這個:

<div class="blue"> 
<div> 
    <div></div> 
    <div></div> 
    <div></div> 
</div> 
<div> 
    <div></div> 
    <div></div> 
    <div></div> 
</div> 

而且這樣的:

.blue {background-color: blue;text-align: center;display: inline-block;padding: 5px;} 
.blue > div > div {background-color: red; width:100px; height: 50px; margin: 10px;display: inline-block;} 

Example on jsfiddle

0

在所有瀏覽器選項不兼容的另一種選擇但不需要浮動:左

.blue{ 
 
    background-color:blue; 
 
    overflow:hidden; 
 
    width: 140px; 
 
    display: flex; 
 
    justify-content: space-around; 
 
    flex-wrap: wrap; 
 
} 
 

 
.blue div{ 
 
    background-color:red; 
 
    margin: 2.5px 0 2.5px 0; 
 
    width:40px; 
 
}
<div class="blue"> 
 
    <div style="height: 40px;"></div> 
 
    <div style="height: 40px;"></div> 
 
    <div style="height: 40px;"></div> 
 

 
    <div style="height: 40px;"></div> 
 
    <div style="height: 40px;"></div> 
 
    <div style="height: 40px;"></div> 
 
</div>