BFC的定義###
先看W3C文檔
In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.
In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch). This is true even in the presence of floats (although a box's line boxes may shrink due to the floats), unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats).
Block Formatting Context,中文直譯為塊級(jí)格式上下文。BFC就是一種布局方式,在這種布局方式下,盒子們自所在的containing block頂部一個(gè)接一個(gè)垂直排列,水平方向上撐滿整個(gè)寬度(除非內(nèi)部盒子自己建立了新的BFC)。兩個(gè)相鄰的BFC之間的距離由margin決定。在同一個(gè)BFC內(nèi)部,兩個(gè)垂直方向相鄰的塊級(jí)元素的margin會(huì)發(fā)生“塌陷”。
文檔這里也間接指出了垂直相鄰盒子margin合并的解決辦法:就是給這兩個(gè)盒子也創(chuàng)建BFC。
通俗一點(diǎn),可以把BFC理解為一個(gè)封閉的大箱子,箱子內(nèi)部的元素?zé)o論如何翻江倒海,都不會(huì)影響到外部。
如何創(chuàng)建BFC###
再來看一下官方文檔怎么說的
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
總結(jié)一下就是:
- float屬性不為none
- overflow不為visible(可以是hidden、scroll、auto)
- position為absolute或fixed
- display為inline-block、table-cell、table-caption
BFC的作用
1. 清除內(nèi)部浮動(dòng)
我們在布局時(shí)經(jīng)常會(huì)遇到這個(gè)問題:對子元素設(shè)置浮動(dòng)后,父元素會(huì)發(fā)生高度塌陷,也就是父元素的高度變?yōu)?。解決這個(gè)問題,只需要把把父元素變成一個(gè)BFC就行了。常用的辦法是給父元素設(shè)置overflow:hidden。
2. 垂直margin合并
在CSS當(dāng)中,相鄰的兩個(gè)盒子的外邊距可以結(jié)合成一個(gè)單獨(dú)的外邊距。這種合并外邊距的方式被稱為折疊,并且因而所結(jié)合成的外邊距稱為折疊外邊距。
折疊的結(jié)果:
- 兩個(gè)相鄰的外邊距都是正數(shù)時(shí),折疊結(jié)果是它們兩者之間較大的值。
- 兩個(gè)相鄰的外邊距都是負(fù)數(shù)時(shí),折疊結(jié)果是兩者絕對值的較大值。
- 兩個(gè)外邊距一正一負(fù)時(shí),折疊結(jié)果是兩者的相加的和。
這個(gè)同樣可以利用BFC解決。關(guān)于原理在前文已經(jīng)講過了。
3. 創(chuàng)建自適應(yīng)兩欄布局
在很多網(wǎng)站中,我們??吹竭@樣的一種結(jié)構(gòu),左圖片+右文字的兩欄結(jié)構(gòu)。
//CSS
*{
margin: 0;
padding: 0;
}
.box {
width:300px;
border: 1px solid #000;
}
.img {
float: left;
}
.info {
background: #f1f1f1;
color: #222;
}
//HTML
<div class="box">
<img src="03.jpg" alt="" class="img">
<p class="info">信息信息信息信息信息信息</p>
</div>
一般情況下,它是這樣的

但是當(dāng)文字多了以后...

顯然,這是文字受到了圖片浮動(dòng)的影響。當(dāng)然,如果你想做文本繞排的效果,浮動(dòng)是不二之選。不過在這里,這顯然不是我們想要的。此時(shí)我們可以為P元素的內(nèi)容建立一個(gè)BFC,讓其內(nèi)容消除對外界浮動(dòng)元素的影響。給文字加上overflow:hidden

兩欄布局就完成了。我們改變圖片的大小:

兩欄布局的結(jié)構(gòu)依然沒有改變,如此就實(shí)現(xiàn)了兩欄自適應(yīng)布局。
參考鏈接:
https://www.w3.org/TR/CSS2/visuren.html#block-formatting
http://www.zhangxinxu.com/wordpress/?p=4588