什么是BFC#
bfc的全称为Block Formatting Contexts,即块级格式化上下文,W3C是这么定义BFC的
https://www.w3.org/TR/CSS2/visuren.html#block-formatting
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). 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的方法:###
- 浮动元素和position属性为absolute的元素
- 非块级盒子的块级容器,如display属性为inline-block,table-cells和table-captions的元素
- overflow属性不为visible的块级盒子(最常用的是overflow: hidden)
BFC的特性:###
- 在一个BFC中的块级元素会从垂直的从上到下排列
- 相邻的两个盒子的间隙是由margin属性决定的
- 相邻的盒子垂直方向的margin会产生重叠现象
- 每个盒子的左边缘会触碰到容器的左边缘(自右向左的除外)
BFC的应用:###
- 消除float的文字环绕效果
这里图片左浮动,文字内容自动环绕
我们给包裹文字的div添加属性overflow: hidden
- 消除margin重叠效果
这里每个红色的div都设置了上下各20px的外边距,可以看出在中间处发生了margin重叠
而我们给下面这个红色的div外面加个div并设置overflow: hidden属性
重叠效果被消除了
结束之言:#
关于BFC的总结,小生就说这么多吧。本文仅供参考,欢迎大家一起来交流