1. 什么是BFC
MDN上是这样说明的
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
2.如何产生BFC
简单来说就是
1、float的值不是none。
2、position的值不是static或者relative。
3、display的值是inline-block、table-cell、flex、table-caption或者inline-flex
4、overflow的值不是visible
3.如何使用
3.1解决高度塌陷
定义两个box,margin设置为100px,按理来说他们的间距应该为200px才对,原因是块的上外边距和下外边距会合并为单个边距,值为单个边距的最大值
<style>
.box{
width: 100px;
height: 100px;
background-color:pink;
margin: 100px;
overflow: hidden;
}
</style>
<div class="box"></div>
<div class="box"></div>
解决办法就是把div放在不同的bfc中
<style>
.container {
overflow: hidden;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
margin: 100px;
}
</style>
<body>
<div class="container">
<div class="box"></div>
</div>
<div class="container">
<div class="box"></div>
</div>
</body>
可以看到成功解决了问题
3.2清除浮动
<style>
.container {
border: 1px solid forestgreen;
}
.box {
float: left;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="container">
<div class="box"></div>
</div>
可以看到给box设置浮动后脱离了文档流,导致container只剩下了2px的border
解决方法给父元素设置为BFC
<style>
.container {
overflow: hidden;
border: 1px solid forestgreen;
}
.box {
float: left;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<div class="container">
<div class="box"></div>
</div>
3.3 阻止元素被浮动元素覆盖
<style>
.box1 {
float: left;
width: 50px;
height: 50px;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<div class="box1"></div>
<div class="box2"></div>
解决办法:给位浮动的元素设置BFC
<style>
.box1 {
float: left;
width: 50px;
height: 50px;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: aqua;
overflow: hidden;
}
</style>
<div class="box1"></div>
<div class="box2"></div>