CSS (BFC)
BFC
display属性为block、list-item、table的元素,会产生BFC
添加如下属性会触发BFC:
float属性不为none
position为absolute或fixed
overflow不为visible的
display为inline-block table-cell、table-caption、flex、inline-flex
布局特性:
- BFC中,盒子从顶端开始一个接一个垂直排列
- 盒子垂直方向的距离由margin决定,属于同一个BFC 的两个相邻盒子的margin会发生重叠
- 在BFC中每个盒子的左外边沿(margin-left)会触碰到容器的左边缘(border-left) (从右往左则是右边缘)
- BFC区域不会与浮动的盒子产生交集,而是紧贴浮动边沿
- 计算BFC高度时,自然也会检测浮动的盒子高度
BFC用途
- 清除浮动(特性5)
.father {
margin: 100px auto;
width: 400px;
border: 2px solid red;
}
.father div:nth-child(1){
width: 200px;
height: 200px;
background-color: #0086b3;
float: left;
}
.father div:nth-child(2) {
width: 200px;
height: 200px;
background-color: #ffff00;
float: left;
} 浮动后父盒子没了高度。
eg. 父盒子加overflow: hidden/auto; 之后。
- 解决外边距合并
.father div:nth-child(1){
width: 200px;
height: 200px;
background-color: #0086b3;
margin-bottom: 50px;
}
.father div:nth-child(2) {
width: 200px;
height: 200px;
background-color: #ffff00;
margin-top: 100px;;
}
两个外边距取了最大,合并了。
方法:分离,使他们不在同一个BFC
.over {
overflow: hidden;
} <div class="father">
<div class="over">
<div class="son1"></div>
</div>
<div class="son2"></div>
</div>
- 制作右侧自适应盒子(特性4)
盒子1浮动,盒子2就会顶上去。
.son1{
width: 200px;
height: 200px;
background-color: #0086b3;
float: left;
}
.son2 {
height: 400px;
background-color: #ffff00;
overflow: hidden;
}
可控制左边宽度增加,就能看见右边自适应效果了。
