BFC (Block formatting context) “块级格式化上下文”
它是页面中的一块渲染区域,有一套渲染规则,决定了其子元素如何布局,以及和其他元素之间的关系和作用。
转载自 前端精选文摘:BFC 神奇背后的原理
触发条件
- 根元素,即HTML元素
- float的值不为none
- overflow的值不为visible
- display的值为inline-block,table-cell,table-caption ,flex,inline-flex
- position为absolute或fixed
布局规则
- 内部的Box会在垂直方向,一个接一个地放置。
- Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
- 每个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
- BFC的区域不会与float box重叠。
- BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
- 计算BFC的高度时,浮动元素也参与计算
特性
1.自适应两栏布局
<style>
body {width: 300px;position: relative;}
.aside {width: 100px;height: 150px;float: left;background: #f66;}
.main {height: 200px;background: #fcc;}
</style>
<body>
<div class="aside"></div>
<div class="main"></div>
</body>
每个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
因此,虽然存在浮动的元素aslide,但main的左边依然会与包含块的左边相接触。 根据BFC布局规则第四条:
BFC的区域不会与float box重叠。
我们可以通过通过触发main生成BFC, 来实现自适应两栏布局。
.main {overflow: hidden;}
当触发main生成BFC后,这个新的BFC不会与浮动的aside重叠。因此会根据包含块的宽度,和aside的宽度,自动变窄。效果如下:
2.清除内部浮动
<style>
.par {border: 5px solid #fcc;width: 300px;}
.child {border: 5px solid #f66;width:100px;height: 100px;float: left;}
</style>
<body>
<div class="par">
<div class="child"></div>
<div class="child"></div>
</div>
</body>
计算BFC的高度时,浮动元素也参与计算
为达到清除内部浮动,我们可以触发par生成BFC,那么par在计算高度时,par内部的浮动元素child也会参与计算。
.par {overflow: hidden;}
3.防止垂直 margin 重叠
可以参考另一篇博客CSS3进阶 — 边距折叠
<style>
p {color: #f55;background: #fcc;width: 200px;line-height: 100px;text-align:center;margin: 100px;}
</style>
<body>
<p>Haha</p>
<p>Hehe</p>
</body>
两个p之间的距离为100px,发送了margin重叠。
Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
我们可以在p外面包裹一层容器,并触发该容器生成一个BFC。那么两个P便不属于同一个BFC,就不会发生margin重叠了。
<style>
.wrap {overflow: hidden;}
p {color: #f55;background: #fcc;width: 200px;line-height: 100px;text-align:center;margin: 100px;}
</style>
<body>
<p>Haha</p>
<div class="wrap">
<p>Hehe</p>
</div>
</body>