zhictory

BFC 的简单理解

BFC 的扩写是 Block formatting contexts (块级格式化上下文),它看不见摸不着但对 CSS 盒模型有影响。
标准里对 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.

同时提到一个前端常见的 collapse 现象:

Vertical margins between adjacent block-level boxes in a block formatting context collapse.

所以笔者是这么理解 BFC 的:

  1. 浮动元素、绝对定位元素、非块盒的块容器(inline-block、table-cell、table-caption 元素)、overflow 不为 visible 的元素会创建 BFC
  2. 同一个 BFC 里,两个相邻的块级盒的垂直外边距会 collapse(塌陷)

也就是说不同的 BFC之间就会消除相邻元素的 collapse,以下是可创建 BFC 的条件:

这里写了个测试 collapse 的 demo,经测试发现:

参考:BFC 的文档