博客原文連接css
W3C關於BFC的描述見block-formattinghtml
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.less
浮動(float),絕對定位元素(absolute, fixed),非塊盒子的塊容器(如
inline-block
,table-cell
和table-caption
),和塊盒子的overflow
值爲非visiblity
(能夠是auto
,hidden
)的元素,將建立塊級格式上下文。ideIn 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.flex
在塊格式上下文中,從塊容器的頂部開始,把盒子一個接一個的垂直排列。兩個相鄰的盒子的垂直距離由
margin
屬性肯定,在塊格式上下文中相鄰塊級盒子的垂直外邊距會重疊。uiIn 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). 在塊格式上下文中,每一個塊級盒子的左外邊緣會和容器塊的左邊緣接觸(從右到左的格式中,右邊緣接觸),即便存在浮動也會如此,除非該塊級盒子創建一個新的塊級格式上下文,因爲浮動,盒子會變窄。設計
經過實例來直觀理解上面的現象code
See the Pen BFC浮動元素 by youcanping2008 ( @youcanping) on CodePen.從右到左的格式中,右邊緣接觸orm
參見MDN 塊格式化上下文 - Web 開發者指南 /| MDNhtm
總結建立塊級格式化上下文的方式分2類:
html
)button
或設置display: inline-block
的元素)td
,table-cell
,table-caption
)。display: flex | inline-flex
)裏的直接子項目;display: grid | inline-grid
)裏的直接子項目;float: [left | right]
);position: [absolute | fixed]
);overflow
爲非默認值visiblity
,如hidden
,auto
, scoll
等;display: flow-root
的元素BFC規範決定元素其內容的定位,及和其餘元素的關係和相互做用。
那麼咱們爲何要這麼執着塊級格式化上下文呢,塊盒子在塊級上下文格式化上下文中會發生什麼現象呢?
垂直外邊距重疊並非一無可取,設計之初是爲了適應文檔的書寫習慣,好比在咱們設置段落的間隔是1倍外邊距,若是沒有外邊距重疊,那麼在WEB中出現外邊距疊加就會出現2倍段落外邊距,外邊距重疊方便了排版,但有時咱們又不但願外邊距重疊,那麼如何解決外邊距重疊問題
根據規範屬於同一個BFC內的塊盒子垂直外邊距會重疊,除非爲該元素創建新的BFC和其餘塊盒子分別屬於不一樣的BFC容器中。
See the Pen BFC解決外邊距重疊問題 by youcanping2008 ( @youcanping) on CodePen.咱們在使用浮動元素時常常會碰到一個問題,塊容器中有浮動元素會出現高度坍塌問題。目前比較流行的解決方案就是使用clearfix
清除浮動方案。
另外一種方案就是創建BFC來規範容器的高度,避免高度坍塌。
See the Pen BFC浮動元素 by youcanping2008 ( @youcanping) on CodePen.塊元素默認老是會挨着父容器的邊緣,即便存在浮動元素,也會接觸父容器邊緣,如下示例中經過給塊元素創建BFC讓元素不接觸父容器的邊緣,實現文字不環繞效果,浮動元素有50%的透明度,能夠看到段落在沒有BFC的狀況下是在浮動元素的下方,但段落中的文字和浮動元素並排顯示,出現文字環繞效果,經過創建BFC段落的寬度邊小了,段落空間被浮動元素擠壓,即出現浮動元素和段落並列顯示效果。
See the Pen BFC文字環繞 by youcanping2008 ( @youcanping) on CodePen.