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.
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).
BFC(块级格式上下文)
定义
可以先看一下官方的定义 BFC
蹩脚英语翻译一下:
创建
由此可以得出,创建
BFC
(块级格式上下文)需要满足以下条件之一:float
不是none
)position
为absolute
或fixed
)display
为inline-blocks
,table-cells
, 和table-captions
overflow
不是visible
的元素使用场景
清除margin折叠
理想情况下两个
p
之间的margin
值应该是20px
, 但是实际上我们发现只有10px
, 因为margin
值发生折叠了我们来 创建一个
BFC
来解决这个问题示例jsfiddle
清除浮动
以上的示例,
div
的高度为 0,因为我们给p
元素加了浮动,脱离了文档流。为了解决这个问题,我们可以给div
加上overflow: hidden;
示例jsfiddle