MDN的解释是BFC
简单来说就是,BFC 是一个完全独立的空间,让空间里的子元素不会影响到外部的布局, BFC可以看做是一个css元素属性来使用
这里简单列举几个触发BFC使用的CSS属性
overflow: hidden
display: inline-block
position: absolute
position: fixed
display: table-cell
display: flex
案例 清除浮动
<style>
.content {
background-color: pink;
}
.box1 {
width: 200px;
height: 200px;
background-color: green;
}
.box2 {
width: 200px;
height: 200px;
background-color: orange;
}
</style>
<div class="content">
<div class="box1"></div>
<div class="box2"></div>
</div>
当.box1 .box2 设置为float:left 之后,两个盒子就会变成浮动流,父盒子无法被撑开,接下来粉色的背景色就看不见了,父盒子剩下边框黑线
这时候 只要给父盒子触发BFC,就可以处理父盒子因为子元素浮动无法撑开的问题
给父元素可以设置为 display:inline-block; 这样清除浮动,本质也是触发了BFC,
案例二 外边距合并
<style>
.box1 {
width: 200px;
height: 200px;
margin-bottom: 20px;
background-color: green;
}
.box2 {
/* position: absolute; */
/* display: inline-block; */
width: 200px;
height: 200px;
margin-top: 20px;
background-color: orange;
}
</style>
<div class="content">
<div class="box1"></div>
<div class="box2"></div>
</div>
我们可以给第二个盒子触发BFC,成为一个独立的空间,这两两个盒子之间的外边距距离就能是40px了
可以给.box2 设置为
/* position: absolute; /
/ display: inline-block; */ 都可以触发box2的BFC
<style>
.box1 {
width: 200px;
height: 200px;
margin-bottom: 20px;
background-color: green;
}
.box2 {
/* position: absolute; */
display: inline-block;
width: 200px;
height: 200px;
margin-top: 20px;
background-color: orange;
}
</style>
<div class="content">
<div class="box1"></div>
<div class="box2"></div>
</div>