BFC的理解
**块级格式化上下文,它指一个独立的块级渲染区域。只有block-level BOX(块级类型的盒子参与)参与,**该区域拥有一套渲染规则来约束块级盒子的布局,并且与区域外部无关。
从一个现象说起
一个盒子不设置height,当内容子元素都浮动时,无法撑起自身
这个盒子没有形成BFC
*如下代码*
<div class="father">
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
</div>
.son{
width:100px;
height:100px;
background:red;
float:left;
}
如何创建BFC
1.float值不是none
2.position 的值不是static或relative
3.display的值是inline-block、flex、或者inline-flex
4.overflow:hidden 方法最好
.father{
/* float: left; */
/* position: absolute; */
/* display: inline-block; */
overflow:hidden
}
BFC的其它作用
BFC可以取消盒子margin塌陷
<style type="text/css">
.father{
width: 100px;
height: 300px;
background-color: yellow;
}
.son{
width: 100px;
height: 100px;
background-color: red;
margin-top: 20px; //这时候把父盒子带下来了,这点叫margin塌陷用BFC可以解决
}
</style>
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
BFC可以阻止元素被浮动元素覆盖
<style type="text/css">
.son{
width: 200px;
height: 200px;
background-color: red;
float: left;
}
.son-last{
width: 200px;
height: 300px;
background-color: black;
overflow: hidden;/* 由于浮动元素会脱离文档流,所以最后一个元素就顶上去了 BFC解决*/
}
</style>
<body>
<div>
<div class="son"></div>
<div class="son"></div>
<div class="son-last"></div>
</div>
</body>