定义
块级格式上下文简称BFC(Block Formatting Context),它是页面中的一个独立渲染区域,决定了其内部子元素如何布局都不会影响到盒子外部的其他元素。常见FC有BFC、IFC、GFC、FFC,后三了解即可。
触发条件(任选其一)
1、根元素<html>
2、float值为left、right,不为none
3、overflow值为hidden、scroll、auto,不为visible
4、position值为absolute、fixed,不为relative
5、display值为inline-block、flex、grid、table-cell、table-caption,不为none、inline、block
BFC特性
1、内部的盒子在垂直方向依次放置
2、在垂直方向上的间距通过margin控制
3、使用BFC的区域不会与float区域重合,并且在计算高度时,浮动元素也会参与计算
4、BFC内部子元素不会影响到外部元素
BFC作用
1、解决外部边距重叠(margin塌陷)
2、解决盒子塌陷
3、清除浮动
4、解决浮动文字环绕问题
解决margin塌陷
示例一(两个独立盒子之间的margin塌陷):
<div class="contain">
<div class="top">top</div>
</div>
<div class="contain">
<div class="bottom">bottom</div>
</div>
<style>
.top {
/* 添加一个margin的下边距 */
margin-bottom: 20px;
width: 100px;
height: 100px;
background-color: pink;
}
.bottom {
/* 添加一个margin的上边距 */
margin-top: 20px;
width: 100px;
height: 100px;
background-color: deeppink;
}
</style>
当未开启BFC时,结果如下:top和bottom均设置了20px外边距,但top和bottom之间最后只有20px间距,出现margin塌陷
解决:将top和bottom的父元素设置over-flow:hidden;
<style>
.contain {
overflow: hidden; /* 下面的几种方法也可以 */
/* display: flex; */
/* display: table-cell; */
/* display: grid; */
/* position: absolute; */
/* float: left; */
}
</style>
解决后的结果:
示例二(父子元素之间的margin塌陷):
<style>
.father {
width: 200px;
height: 200px;
background-color: skyblue;
}
.child {
/* 添加一个margin的上边距 */
margin-top: 20px;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="father">
<div class="child"></div>
</div>
当父元素未开启BFC时,结果如下:子元素设置的margin-top未能在父子元素之间形成间距
解决:给父元素追加下面样式
<style>
.father{
overflow: hidden; /* 上面提到的几种方法也可以 */
}
</style>
结果:
解决盒子高度塌陷
示例
<style>
.father {
width: 200px;
background-color: skyblue;
}
.child {
/* 设置浮动 */
float: left;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="father">
<div class="child"></div>
</div>
未给父元素设置高度,给子元素设置浮动,结果:父元素高度为0
解决:给父元素追加下面样式开启BFC
<style>
.father{
overflow: hidden; /* 上面提到的几种方法也可以 */
}
</style>
结果:
清除浮动
<style>
.left {
float: left;
width: 100px;
background-color: skyblue;
}
.right {
width: 200px;
height: 100px;
background-color: pink;
}
</style>
<div class="left">左侧内容</div>
<div class="right">右侧内容</div>
结果:
解决:对right元素追加以下样式开启BFC:
<style>
.right{
overflow: hidden; /* 上面提到的几种方法也可以 */
}
</style>
结果:
解决浮动文字环绕问题
<style>
.contain {
width: 200px;
border: 1px solid black;
}
.box {
float: left;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="contain">
<div class="box"></div>
<p>解决浮动环绕文字问题;解决浮动环绕文字问题;解决浮动环绕文字问题;解决浮动环绕文字问题;解决浮动环绕文字问题;解决浮动环绕文字问题</p>
</div>
结果:
解决:给p元素开启BFC
<style>
p{
overflow: hidden; /* 上面提到的几种方法也可以 */
}
</style>
结果:
参考这位大佬:https://juejin.cn/post/7097522237044949000