什么是BFC?
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
个人理解就是BFC的触发会让盒子形成封闭空间与外部元素布局互不影响。
BFC触发条件:
- html根元素(其实BFC就是构造了一个和根元素类似的盒子)
- 浮动元素:float 除 none 以外的值
- 绝对定位元素:position (absolute、fixed)
- display 为 inline-block、table-cells、flex
- overflow 除了 visible 以外的值 (hidden、auto、scroll)
注释:还有其他的触发方式,只是兼容性不好,这里不提出详情:
触发条件的对比:
- float会导致盒子浮动,对盒子兄弟有影响;
- 绝对定位,会脱离文档流,盒子会改变原生的一些样式;
- dispaly也会改变盒子的原有特性;
- overflow比较好,如果盒子宽高没有定死,不会出现裁剪的情况(建议使用的方式)
应用场景:
- 子元素浮动引起父元素塌陷
<style>
body {
padding: 20px;
}
.father {
border: 1px solid;
}
.box {
background-color: red;
height: 50px;
width: 50px;
float: left;
}
</style>
<body>
<div class="father">
<div class="box"></div>
我是有内容的
</div>
</body>
解决办法:
1.在father元素上设置overflow: hidden;父元素还是占文档流的一行,表现为块级元素
2.在father元素上设置position: absolute;父元素由于脱离文档流,表现为一个行内元素
- 父子元素margin区域重合
<style>
body {
padding: 20px;
}
.father {
/* border: 1px solid; */很特殊,也会是父子margin的分离
background-color: yellow;
height: 400px;
.box {
background-color: red;
height: 50px;
width: 50px;
margin-top: 10px;
}
</style>
<body>
<div class="father">
<div class="box"></div>
</div>
</body>
解决办法:
1.建设使用overflow: hidden;触发BFC
2.给父元素设置border也能分离父子元素的magin
- 兄弟元素margin重合取大的
<style>
body {
padding: 20px;
}
.father {
border: 1px solid;
/* background-color: yellow; */
height: 400px;
}
.box {
background-color: red;
height: 50px;
width: 50px;
margin-bottom: 50px;
}
.box1 {
background-color: yellow;
height: 50px;
width: 50px;
margin-top: 10px;
}
</style>
<body>
<div class="father">
<div class="box"></div>
<div class="box1"></div>
</div>
</body>
解决办法:
1在一个div外面套一个div然后触发该div的BFC
2直接在后面的子元素设置position:absolute;
- 自适应布局,左右与上下布局中的铺满解决方案中的应用