BFC全稱Block Formatting Context ,直譯「塊級格式化上下文」,也有譯做「塊級格式化範圍」。它是 W3C CSS 2.1 規範中的一個概念,它決定了元素如何對其內容進行定位,以及與其餘元素的關係和相互做用。通俗的講,就是一個div內部,咱們用float和margin佈局元素。css
1.自適應佈局html
<style> body { width: 300px; position: relative; } .aside { width: 100px; height: 150px; float: left; background: #f66; } .main { height: 200px; background: #fcc; } </style> <body> <div class="aside"></div> <div class="main"></div> </body>
根據BFC
佈局規則第3條:ide
每一個元素的margin box的左邊, 與包含塊border box的左邊相接觸(對於從左往右的格式化,不然相反)。即便存在浮動也是如此。wordpress
所以,雖然存在浮動的元素aslide,但main的左邊依然會與包含塊的左邊相接觸。佈局
根據BFC
佈局規則第四條:post
BFC
的區域不會與float box
重疊。flex
咱們能夠經過經過觸發main生成BFC
, 來實現自適應兩欄佈局。spa
當觸發main生成BFC
後,這個新的BFC
不會與浮動的aside重疊。所以會根據包含塊的寬度,和aside的寬度,自動變窄。效果以下:3d
2.清除內部浮動code
<style> .par { border: 5px solid #fcc; width: 300px; } .child { border: 5px solid #f66; width:100px; height: 100px; float: left; } </style> <body> <div class="par"> <div class="child"></div> <div class="child"></div> </div> </body>
頁面效果:
根據BFC
佈局規則第六條:
計算
BFC
的高度時,浮動元素也參與計算
爲達到清除內部浮動,咱們能夠觸發par生成BFC
,那麼par在計算高度時,par內部的浮動元素child也會參與計算。
代碼:
.par { overflow: hidden; }
效果以下:
<style> p { color: #f55; background: #fcc; width: 200px; line-height: 100px; text-align:center; margin: 100px; } </style> <body> <p>Haha</p> <p>Hehe</p> </body>
頁面效果:
兩個p之間的距離爲100px,發送了margin重疊。
根據BFC佈局規則第二條:
Box
垂直方向的距離由margin決定。屬於同一個BFC
的兩個相鄰Box
的margin會發生重疊
咱們能夠在p外面包裹一層容器,並觸發該容器生成一個BFC
。那麼兩個P便不屬於同一個BFC
,就不會發生margin重疊了。
代碼:
<style> .wrap { overflow: hidden; } p { color: #f55; background: #fcc; width: 200px; line-height: 100px; text-align:center; margin: 100px; } </style> <body> <p>Haha</p> <div class="wrap"> <p>Hehe</p> </div> </body>
效果以下:
BFC
就是頁面上的一個隔離的獨立容器,容器裏面的子元素不會影響到外面的元素。反之也如此。
由於BFC
內部的元素和外部的元素絕對不會互相影響,所以, 當BFC
外部存在浮動時,它不該該影響BFC
內部Box的佈局,BFC
會經過變窄,而不與浮動有重疊。一樣的,當BFC
內部有浮動時,爲了避免影響外部元素的佈局,BFC
計算高度時會包括浮動的高度。避免margin重疊也是這樣的一個道理。
摘抄自:
http://www.cnblogs.com/lhb25/p/inside-block-formatting-ontext.html
參考文章:
http://www.zhangxinxu.com/wordpress/2015/02/css-deep-understand-flow-bfc-column-two-auto-layout/
http://www.w3cplus.com/css/understanding-bfc-and-margin-collapse.html
http://cssor.com/css-bfc-block-formatting-context.html