BFC(块级格式上下文)的理解
BFC(块级格式上下文)
定义
可以先看一下官方的定义 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. 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).
蹩脚英语翻译一下:
浮动元素,绝对定位元素,非块级盒子的块状元素(类似
inline-blocks,table-cells, 和table-captions),还有overflow不是visible的块状元素,将会为它们的内容建立新的块级格式上下文。 在块级格式上下文中,盒子会一个接一个地从容器的上方开始垂直排列下来。两个相邻的盒子之间的垂直距离由margin属性撑开,在块级格式上下文中,两个相邻的块级盒子margin值会造成塌陷。 在一个块级格式上下文中,每一个盒子的左边边缘将会触碰到容器的左边边缘(对于从右到左排列的,右边边缘将会触碰到容器的右边缘)。
创建
由此可以得出,创建 BFC(块级格式上下文)需要满足以下条件之一:
- 浮动元素(元素的
float不是none) - 绝对定位元素(元素的
position为absolute或fixed) -
display为inline-blocks,table-cells, 和table-captions -
overflow不是visible的元素
使用场景
清除margin折叠
<p></p>
<p></p>
p{
width: 50px;
height: 50px;
background-color: yellow;
margin: 10px 0;
}
理想情况下两个 p 之间的 margin 值应该是 20px, 但是实际上我们发现只有 10px, 因为 margin 值发生折叠了
我们来 创建一个 BFC 来解决这个问题
<p></p>
<div>
<p></p>
</div>
div{
overflow: hidden;
}
p{
width: 50px;
height: 50px;
background-color: yellow;
margin: 10px 0;
}
清除浮动
<div>
<p></p>
<p></p>
</div>
p{
width: 50px;
height: 50px;
background-color: yellow;
float: left;
margin: 10px;
}
以上的示例, div 的高度为 0,因为我们给 p 元素加了浮动,脱离了文档流。为了解决这个问题,我们可以给 div 加上 overflow: hidden;