- 在討論BFC的特點之前,先得了解一下邊距重疊問題。
- 父子元素邊距重疊:當父元素爲非BFC時,第一個子元素的margin-top會重疊到父元素的margin-top。
<section>
<style>
#bfc3{
background-color:deeppink;
height: 50px;
}
#bfc4{
height: 50px;
background-color: darksalmon;
margin-top: 0px;
width: 400px;
}
</style>
<div id="bfc3">
<div id="bfc4">
<p>父子重疊</p>
</div>
</div>
</section>
效果:
- 兄弟元素邊距重疊:當兩個相鄰的元素爲非BFC時,前者的margin-bottom和後者的margin-top會重疊。
- 空元素邊距重疊:當空元素設置了margin-top和margin-bottom時,兩個margin會重疊。
- BFC的概念
Formatting Context:指頁面中的一個渲染區域,並且擁有一套渲染規則,他決定了其子元素如何定位,以及與其他元素的相互關係和作用。
BFC:塊級格式化上下文,它是指一個獨立的塊級渲染區域,只有Block-level BOX參與,該區域擁有一套渲染規則來約束塊級盒子的佈局,且與區域外部無關。 - BFC的原理
- BFC區域的元素不會影響外面的元素,反之亦然。
- BFC區域不會與float元素髮生重疊
- 計算BFC高度時,浮動元素能夠撐開BFC的高度,達到清除浮動的效果。
<section>
<style>
#bfc1{
background-color:deeppink;
overflow: auto;
}
#bfc2{
height: 50px;
background-color: darksalmon;
margin-top: 30px;
float: left;
width: 400px;
}
</style>
<div id="bfc1">
<div id="bfc2">
<p>浮動元素能夠撐開父元素的高度</p>
</div>
</div>
</section>
效果:父元素高度被浮動元素撐開
- 根據BFC的原理,可以解決邊距重疊問題,當不想讓兩個元素相互影響時,可以對兩個元素創建BFC,這樣就不會發生邊距重疊的問題。對於父子元素邊距重疊問題,只需對父元素創建BFC,則可解決父子重疊。
- 如何創建BFC
- overflow 除了 visible 以外的值 (hidden、auto、scroll)
- 設置float不爲none
- 設置position不爲relative和static(absolute,fixed,sticky)
- 設置display爲table-cell,flex,inline-block