2016-11-11 67 views
2

我一直有一個非常奇怪的CSS問題。我的一些網頁在元素之間顯示了一個無法解釋的「空間」。檢查代碼表明這個空間不屬於任何元素。CSS最小高度添加到子元素的底部邊距

我縮小了範圍,我想我知道爲什麼會發生這個問題。但我想知道,爲什麼發生這種情況。

的問題,我認爲,是min-height: 50px#outer選擇增加了的#inner下面#outer下邊距,這導致上述的原因不明的空間。如果將其替換爲height: 50px,則該空間將消失。

這發生在Chrome上,但不是FireFox。

我的理論是,Chrome的CSS先列出元素,然後檢查是否滿足最小高度要求。如果沒有,那麼它會延長div的高度,並推動「無法解釋的空間」。它必須複製或繼承子元素的底部邊距。我認爲這隻發生在底部邊緣。

我試過這個理論的兩個測試,加入padding: 1px;和加入overflow: hidden;它們都導致div的高度包括它的孩子,從而擺脫了問題。雖然,我認爲在overflow: hidden的情況下,它更多地切斷了飛越的內容。

但我沒有CSS的專家,這一切都只是我的一部分,這就是爲什麼我想提出這個的問題:)

這裏猜測是代碼

#outer { 
 
    background-color: blue; 
 
    min-height: 100px; 
 
} 
 
#inner { 
 
    background-color: red; 
 
    height: 50px; 
 
    margin-bottom: 50px; 
 
} 
 
#bottom { 
 
    background-color: green; 
 
    height: 50px; 
 
}
<div id="outer"> 
 
    <div id="inner"> 
 
    </div> 
 
</div> 
 
<div id="bottom"> 
 
</div>

回答

1

此發生是由於margin collapsing - 特異性的innermargin-bottom塌陷成爲margin-bottomouter元素。

解決方案

給一個borderouter件,以防止塌陷保證金 - 見下面的演示:

#outer { 
 
    background-color: blue; 
 
    min-height: 100px; 
 
    border: 1px solid blue; 
 
} 
 
#inner { 
 
    background-color: red; 
 
    height: 50px; 
 
    margin-bottom: 50px; 
 
} 
 
#bottom { 
 
    background-color: green; 
 
    height: 50px; 
 
}
<div id="outer"> 
 
    <div id="inner"> 
 
    </div> 
 
</div> 
 
<div id="bottom"> 
 
</div>

相關問題