博客原文连接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.