一、什麼是BFC
Formatting context 是 W3C CSS2.1 規範中的一個概念。它是頁面中的一塊渲染區域,並且有一套渲染規則,它決定了其子元素將如何定位,以及和其他元素的關係和相互作用。最常見的 Formatting context 有 Block fomatting context (簡稱BFC)和 Inline formatting context (簡稱IFC)。Block formatting context直譯為"塊級格式化上下文"。它是一個獨立的渲染區域,只有Block-level box參與, 它規定了內部的Block-level Box如何佈局,並且與這個區域外部毫不相干。通俗地講,BFC是一個容器,用於管理塊級元素。
二、如何建立BFC
- float為 left|right
- overflow為 hidden|auto|scroll
- display為 table-cell|table-caption|inline-block|inline-flex|flex
- position為 absolute|fixed
- 根元素
三、BFC佈局規則:
- 內部的Box會在垂直方向,一個接一個地放置(即塊級元素獨佔一行)。
- BFC的區域不會與float box重疊(利用這點可以實現自適應兩欄佈局)。
- 內部的Box垂直方向的距離由margin決定。屬於同一個BFC的兩個相鄰Box的margin會發生重疊(margin重疊三個條件:同屬於一個BFC;相鄰;塊級元素)。
- 計算BFC的高度時,浮動元素也參與計算。(清除浮動 haslayout)
- BFC就是頁面上的一個隔離的獨立容器,容器裡面的子元素不會影響到外面的元素。反之也如此。
四、 BFC有哪些特性
特性1:BFC會阻止垂直外邊距摺疊
按照BFC的定義,只有同屬於一個BFC時,兩個元素才有可能發生垂直margin的重疊,這個包括相鄰元素或者巢狀元素,只要他們之間沒有阻擋(比如邊框、非空內容、padding等)就會發生margin重疊。
①相鄰兄弟元素margin重疊問題
<style>
p{
color: #fff;
background: #888;
width: 200px;
line-height: 100px;
text-align:center;
margin: 100px;
}
</style>
<body>
<p>ABC</p>
<p>abc</p>
</body>
複製程式碼

<style>
p{
color: #fff;
background: #888;
width: 200px;
line-height: 100px;
text-align:center;
margin: 100px;
}
.wrap{
overflow:hidden;
}
</style>
<body>
<p>ABC</p>
<div class="wrap">
<p>abc</p>
</div>
</body>
複製程式碼

②父子元素margin重疊問題
<style>
.box{
width:100px;
height:100px;
background:#ccc;
}
.wrap {
background:yellow;
}
.wrap h1{
background:pink;
margin:40px;
}
</style>
<body>
<div class="box">box</div>
<div class="wrap">
<h1>h1</h1>
</div>
</body>
複製程式碼


特性2:BFC不會重疊浮動元素
利用這個特性,我們可以創造自適應兩欄佈局。
<style>
.box1{
height: 100px;
width: 100px;
float: left;
background: lightblue;
}
.box2{width: 200px;
height: 200px;
background: #eee;
}
</style>
<body>
<div class="box1">我是一個左浮動的元素</div>
<div class="box2">喂喂喂!大家不要生氣嘛,生氣會犯嗔戒的。悟空你也太調皮了,
我跟你說過叫你不要亂扔東西,你怎麼又……你看,我還沒說完你就把棍子給扔掉了!
月光寶盒是寶物,你把它扔掉會汙染環境,要是砸到小朋友怎麼辦,就算砸不到小朋友,
砸到花花草草也是不對的。</div>
</body>
複製程式碼


特性3:BFC可以包含浮動----清除浮動
我們都知道浮動會脫離文件流,接下來我們看看下面的例子:
<style>
.box1{
width:100px;
height:100px;
float:left;
border: 1px solid #000;
}
.box2{
width:100px;
height:100px;
float:left;
border: 1px solid #000;
}
.box{
background:yellow
}
</style>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
複製程式碼

由於容器內兩個div元素浮動,脫離了文件流,父容器內容寬度為零(即發生高度塌陷),未能將子元素包裹住。解決這個問題,只需要把把父元素變成一個BFC就行了。常用的辦法是給父元素設定overflow:hidden。
