> For the complete documentation index, see [llms.txt](https://bvct1742.gitbook.io/one-book/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bvct1742.gitbook.io/one-book/knowledge/js/bfc.md).

# BFC

`Box` 是 `CSS` 布局的对象和基本单位，页面是由若干个 `Box` 组成的。 元素的类型 和 `display` 属性，决定了这个 `Box` 的类型。不同类型的 `Box` 会参与不同的 `Formatting Context`。

#### Formatting Context

`Formatting Context` 是页面的一块渲染区域，并且有一套渲染规则，决定了其子元素将如何定位，以及和其它元素的关系和相互作用。 `Formatting Context` 有 `BFC (Block formatting context)`，`IFC (Inline formatting context)`，`FFC (Flex formatting context)` 和 `GFC (Grid formatting context)`。`FFC` 和 `GFC` 为 `CC3` 中新增。

#### BFC 布局规则

* `BFC` 内，盒子依次垂直排列。
* `BFC` 内，两个盒子的垂直距离由 `margin` 属性决定。属于同一个 `BFC` 的两个相邻 `Box` 的 `margin` 会发生重叠【符合合并原则的 `margin` 合并后是使用大的 `margin`】
* `BFC` 内，每个盒子的左外边缘接触内部盒子的左边缘（对于从右到左的格式，- 右边缘接触）。即使在存在浮动的情况下也是如此。除非创建新的 `BFC`。
* `BFC` 的区域不会与 `float box` 重叠。
* `BFC` 就是页面上的一个隔离的独立容器，容器里面的子元素不会影响到外面的元素。反之也如此。
* 计算 `BFC` 的高度时，浮动元素也参与计算。

#### 如何创建 BFC

* 根元素
* 浮动元素（`float` 属性不为 `none`）
* `position` 为 `absolute` 或 `fixed`
* `overflow` 不为 `visible` 的块元素
* `display` 为 `inline-block`, `table-cell`, `table-caption`

#### BFC 的应用

* 防止 `margin`  重叠 (同一个 `BFC` 内的两个两个相邻 `Box` 的 `margin` 会发生重叠，触发生成两个 `BFC`，即不会重叠)
* 清除内部浮动 (创建一个新的 `BFC`，因为根据 `BFC` 的规则，计算 `BFC` 的高度时，浮动元素也参与计算)
* 自适应多栏布局 (`BFC` 的区域不会与 `float box` 重叠。因此，可以触发生成一个新的 `BFC`)
