BFC定义和作用

1,161 阅读1分钟

BFC

定义:BFC(Block Formatting Context)全称是块级格式化上下文。 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。

实现

1、根元素 (body);

2、浮动 float 不为none;

3、绝对定位元素 position:absolute/fixed;

4、display 为 inline-block、table(相关)、flex、grid;

5、overflow 值不为 visible 的块元素;

作用实例

内部元素浮动引起的高度塌陷

.box {
    width: 200px;
    background-color: #fff;
    border: 1px solid #eee;
    padding: 10px;
}
.box > div {
    width: 100px;
    height: 100px;
    background-color: green;
    float: left;
}
<div class="box">
    <div></div>
</div>

内部元素margin-bottom和margin-top重合/外边距塌陷

.green {
    width: 200px;
    height: 100px;
    margin: 10px 0;
    background-color: green;
}
.red {
    width: 200px;
    height: 100px;
    margin: 10px 0;
    background-color: red;
}
<div class="box">
    <div class="green"></div>
    <div class="red-box">
        <div class="red"></div>
    </div>
</div>

.red-box{display:flow-root;}