外邊距摺疊
塊級元素的上外邊距和下外邊距有時會合並(或摺疊)爲一個外邊距,其大小取其中的最大者,這種行爲稱爲外邊距摺疊(margin collapsing),有時也翻譯爲外邊距合併。
<!-- 外邊距摺疊演示 -->
<div class="collapesd-test">
<div id="top-div"></div>
<div id="bottom-div"></div>
</div>
.collapesd-test {
margin: 20px;
border: 1px solid #808080;
}
#top-div {
width: 50px;
height: 50px;
margin-bottom: 50px;
background-color: #808080
}
#bottom-div {
width: 100px;
height: 100px;
margin-top: 30px;
background-color: #100100;
}
以上代碼會產生外邊距摺疊問題,#top-div
與 #bottom-div
之間分別定義了外邊距50px
與30px
,而實際上加載時兩個div之間的邊距爲50px
。
會發生外邊距摺疊的三種基本情況
相鄰元素之間
毗鄰的兩個元素之間的外邊距會摺疊(除非後一個元素需要清除之前的浮動)。
情況如上圖。
父元素與其第一個或最後一個子元素之間
如果在父元素與其第一個子元素之間不存在邊框、內邊距、行內內容,也沒有創建塊格式化上下文、或者清除浮動將兩者的 margin-top 分開;或者在父元素與其最後一個子元素之間不存在邊框、內邊距、行內內容、height
、min-height
、max-height
將兩者的 margin-bottom
分開,那麼這兩對外邊距之間會產生摺疊。此時子元素的外邊距會“溢出”到父元素的外面。
<!-- 父元素與子元素上下邊距摺疊 -->
<div class="collapesd-test">
<div id="father-div">
<div id="child-div"></div>
</div>
</div>
#father-div {
background-color: #100100
}
#child-div {
width: 50px;
height: 50px;
margin: 50px;
background-color: #808080
}
空的塊級元素
如果一個塊級元素中不包含任何內容,並且在其 margin-top
與 margin-bottom
之間沒有邊框、內邊距、行內內容、height、min-height
將兩者分開,則該元素的上下外邊距會摺疊。
解決方案:
1. 設置padding或者border
如果把div
看做是細胞,padding
和border
就好比細胞膜,因爲沒有東西阻隔外邊距之間互相滲透,導致摺疊。
舉第三種情況爲例,爲#empty-div添加padding屬性,即可避免外邊距摺疊。
CSS
#empty-div {
margin: 50px;
padding: 1px;
}
2. 觸發BFC
BFC:塊格式化上下文(Block Formatting Context,BFC) 是Web頁面的可視化CSS渲染的一部分,是佈局過程中生成塊級盒子的區域,也是浮動元素與其他元素的交互限定區域。
簡單來說,BFC規定了內部塊級元素如何佈局。
以下方式都可以觸發BFC:
- 根元素或包含根元素的元素(
html
) - 浮動元素(元素的
float
不爲none
) - 絕對定位元素(元素的
position
爲absolute
或fixed
) - 行內塊元素(元素的
display
爲inline-block
) - 表格單元格(元素的
display
爲table-cell
,HTML表格單元格默認爲該值) - 表格標題(元素的
display
爲table-caption
,HTML表格標題默認爲該值) - 匿名錶格單元格元素(元素的
display
爲table
、table-row
、
table-row-group
、table-header-group
、table-footer-group
(分別是HTML
table
、row
、tbody
、thead
、tfoot
的默認屬性)或inline-table
) overflow
值不爲visible
的塊元素display
值爲flow-root
的元素contain
值爲layout
、content
或strict
的元素- 彈性元素(
display
爲flex
或inline-flex
元素的直接子元素) - 網格元素(
display
爲grid
或inline-grid
元素的直接子元素) - 多列容器(元素的
column-count
或column-width
不爲auto
,包括column-count
爲 1) column-span
爲all
的元素始終會創建一個新的BFC
,即使該元素沒有包裹在一個多列容器中(標準變更,Chrome bug
)。
參考資料:
MDN