BFC 规范
1. 概念
BFC (Block Formatting Context,块级格式上下文) 是页面上的一个隔离的独立容器。
- 容器里的子元素不会影响到外面的元素
- 反之亦然
示例
一个盒子不设置 height,当内容子元素都浮动时,无法撑起自身。
原因: 这个盒子没有形成 BFC。
2. 创建 BFC
2.1 创建 BFC 的方法
| 方法 | 说明 | 备注 |
|---|---|---|
float 的值不是 none | float: left 或 right | 可以实现,但没有意义,不可能随意给盒子设置浮动 |
position 的值不是 static 或 relative | position: absolute 或 fixed | 可以实现,但不靠谱 |
display 的值是 inline-block、flex 或 inline-flex | 改变显示类型 | 可以实现,但没有意义,可能随便改变盒子的显示类型 |
overflow: hidden | 溢出隐藏 | 最佳方法,但有时不满足所有场景 |
2.2 溢出隐藏
.box {
overflow: hidden;
}作用:
- 溢出盒子边框的内容将会被隐藏
overflow: hidden;是非常好用的让盒子形成 BFC 的方法
2.3 创建 BFC 示例
.box {
width: 500px;
border: 5px solid red;
/* 方法1: float 的值不是 none */
/* float: left; */
/* 方法2: position 的值不是 static 或者 relative */
/* position: absolute; */
/* 方法3: display 的值是 inline-block、flex 或 inline-flex */
/* display: inline-block; */
/* display: flex; */
/* display: inline-flex; */
/* 方法4: overflow: hidden; */
overflow: hidden;
}
.box .c1 {
width: 200px;
height: 200px;
background-color: orange;
float: left;
}
.box .c2 {
width: 200px;
height: 200px;
background-color: skyblue;
float: left;
}<div class="box">
<div class="c1"></div>
<div class="c2"></div>
</div>效果: 父元素能够包裹浮动的子元素,不再高度塌陷
3. BFC 的其他作用
3.1 BFC 可以取消盒子 margin 塌陷
p {
width: 200px;
height: 200px;
background-color: orange;
margin: 50px; /* 垂直方向上下 margin 会重合,距离依然是 50 */
}
/* BFC 作用: 可以取消盒子 margin 塌陷 */
div {
overflow: hidden;
}<div>
<p></p>
</div>
<div>
<p></p>
</div>3.2 BFC 可以阻止元素被浮动元素覆盖
.box1 {
width: 300px;
height: 300px;
background-color: skyblue;
float: left;
}
.box2 {
width: 200px;
height: 200px;
background-color: tomato;
/* 形成BFC,不会被浮动元素覆盖 */
overflow: hidden;
}<section class="box1"></section>
<section class="box2"></section>注意:
- 这个方法没有实际意义,实际开发不会这么用
- 只具有理论意义,要明白
- 需要并排显示的盒子,要么都浮动,要么都不写
- 以下的写法是不合法规范的
4. 浏览器差异
4.1 IE6、7 浏览器的差异
- IE6、7 浏览器使用 hasLayout 机制
- 和 BFC 规范略有差异
- 比如: IE 浏览器可以使用
zoom: 1属性,让盒子拥有 layout
4.2 兼容性处理
如果要制作兼容到 IE6、7 的网页时:
- 尽量让网页布局变得简单
- 内部有浮动的盒子要设置 height 属性
- 规范编程,就没有问题
兼容性示例
.box {
/* 现代浏览器: 形成 BFC */
overflow: hidden;
/* IE6、7: 触发 hasLayout */
*zoom: 1;
}5. BFC 应用场景
5.1 清除浮动
.container {
overflow: hidden;
}
.item {
float: left;
}5.2 防止 margin 塌陷
.parent {
overflow: hidden;
}
.child {
margin: 20px 0;
}5.3 两列布局
.container {
overflow: hidden;
}
.left {
width: 200px;
float: left;
}
.right {
overflow: hidden; /* 创建 BFC */
height: 200px;
background: #f0f0f0;
}6. 总结
BFC 规范关键要点:
BFC 概念:
- Block Formatting Context (块级格式上下文)
- 隔离的独立容器
- 子元素不影响外部元素
创建 BFC 的方法:
float不为noneposition不为static或relativedisplay为inline-block、flex或inline-flexoverflow: hidden(推荐)
BFC 的作用:
- 解决父元素高度塌陷
- 取消 margin 塌陷
- 阻止元素被浮动元素覆盖
- 实现两列布局
浏览器差异:
- IE6、7 使用 hasLayout 机制
- 可用
zoom: 1触发 - 建议尽量简化布局
最佳实践:
- 优先使用
overflow: hidden - 注意兼容性处理
- 合理使用 BFC 解决布局问题
- 优先使用
注意事项:
overflow: hidden会隐藏溢出内容- 不适合所有场景
- 选择合适的 BFC 创建方法