#BFC的理解
- 块级格式化上下文,它是指一个独立的块级渲染区域,只有Block-level
BOX参与,该区域拥有一套渲染规则来约束块级盒子的布局,且与区域外部无关。
#从一个现象开始说起
- 一个盒子不设置height,当内容子元素都浮动时,无法撑起自身
- 这个盒子没有形成BFC
#如何创建BFC
- 方法①: float的值不是none
- 方法②: position的值不是static或者relative
- 方法③: display的值是inline-block、flex或者inline-flex方法
- 方法④: overflow: hidden;(最好的处理方式)
#BFC的其他作用
- BFC可以取消盒子margin塌陷
- 想要的效果:
<style>
*{margin:0; padding:0;}
.father{
width: 200px;
height: 300px;
background-color: red;
overflow: hidden; /*防止margin坍塌*/
}
.son{
width: 200px;
height: 100px;
margin-top: 20px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
- BFC可以可以阻止元素被浮动元素覆盖
<style>
*{margin:0; padding:0;}
.son{
width: 200px;
height: 200px;
background-color: blueviolet;
float:left;
}
.son-last{
width: 200px;
height: 300px;
background-color: brown;
overflow: hidden; /*构建BFC,使之布局与外部无关联*/
}
</style>
</head>
<body>
<div class="son"></div>
<div class="son"></div>
<div class="son-last"></div>
</body>