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.
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.
在BFC中,盒子(Boxes)从包含容器的顶部开始,一个接一个在垂直方向排列;
相邻盒子的垂直距离由他们的margin属性决定;
在BFC中相邻的块级盒子(Block-Level Boxes)的垂直边距会发生重叠。
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).
实现左右自适应布局
这个应用是根据BFC特性的第二段表述来的。
一个常见的布局场景是左右两栏,左边固定宽度,右边自适应宽度。
我们在一个BFC内添加左右两个盒子,左边固定宽度的盒子使用左浮动布局,此时两个盒子的外边框都和容器的左边框接触,而且左边盒子覆盖在它兄弟元素(以下称作右盒子)的上方。
如果此时右盒子内填充大量的文字,把右盒子高度撑开,高于左盒子,就会形成文字环绕效果。
根据BFC的特性unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats),如果将右边盒子构建成一个新的BFC,右边盒子的外边框就不会紧挨着容器的左边框,而是排在左边盒子的后面,此时右边盒子的宽度会收缩(从原来的充满容器宽度变为充满左边盒子剩余的容器宽度)。
特征
以上是来自W3C的定义,总结一下就是以下特征:
float
不为none
);position
不为static
或者relative
);block box
)的块级容器(display
等于inline-block
、table-cell
或者table-caption
);overflow
不为visible
的元素。表现
Boxes
)从包含容器的顶部开始,一个接一个在垂直方向排列;margin
属性决定;Block-Level Boxes
)的垂直边距会发生重叠。margin box
)与容器的左边框相接触(如果是从右向左的格式化,则是与右边框接触);应用
clear: both;
属性来清除浮动;这种方式需要引入一个空白的子元素或者给父元素添加伪类才能实现,如果把父元素显式构造成BFC,也可以解决这个问题。unless the box establishes a new block formatting context (in which case the box itself may become narrower due to the floats)
,如果将右边盒子构建成一个新的BFC,右边盒子的外边框就不会紧挨着容器的左边框,而是排在左边盒子的后面,此时右边盒子的宽度会收缩(从原来的充满容器宽度变为充满左边盒子剩余的容器宽度)。参考