BFC
BFC全称是Block Formatting Context,即块格式化上下文。它是CSS2.1规范定义的,属于 CSS渲染定位的一个概念。
块格式化上下文是 Web页面的可视 CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
避免外边距合并
因为 BFC 元素与浮动元素不重叠得特性,有助于避免/解决外边框合并。
清除浮动
高度塌陷的情况在使用浮动属性时常见,一般是通过清除浮动来解决的。
BootStrap 中通过伪元素的实现来清除浮动
// https://getbootstrap.com/docs/4.0/utilities/clearfix/
// Mixin itself
@mixin clearfix() {
&::after {
display: block;
content: "";
clear: both;
}
}
但我们在内容中创建 BFC ,它是已个特殊布局,所有东西包括在内。
<div class="outer overflow">
<div class="float">I am a floated element.</div>
The outer has overflow: auto.
</div>
.outer {
border: 5px dotted rgb(214,129,137);
border-radius: 5px;
width: 450px;
padding: 10px;
margin-bottom: 40px;
}
.float {
padding: 10px;
border: 5px solid rgba(214,129,137,.4);
border-radius: 5px;
background-color: rgba(233,78,119,.4);
color: #fff;
float: left;
width: 200px;
margin: 0 20px 0 0;
}
.overflow {
overflow: auto;
}
阻止浮动内容环绕
左浮动会导致文本在容器中围绕着浮动,如果给内容添加 BFC 特性,很容易就完成了左右布局。
.text {
overflow: auto;
}