# BFC 笔记
# BFC(Block formatting contexts),块级格式化上下文,只有 block box (block,list-item,table 元素)参与布局,内部区域不受外界影响。
创建一个 bfc:
- 浮动元素。
- 绝对定位和 fixed 定位元素。
- display:inline-block,display: table-cell,display: table-caption,display:table
- overflow 不是 visible
- html 元素
- display: flow-root,column-span: all
BFC 的布局规则 内部的 Box 会在垂直方向,一个接一个地放置。
Box 垂直方向的距离由 margin 决定。属于同一个 BFC 的两个相邻 Box 的 margin 会发生重叠。
每个盒子(块盒与行盒)的 margin box 的左边,与包含块 border box 的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
BFC 的区域不会与 float box 重叠。
BFC 就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
计算 BFC 的高度时,浮动元素也参与计算。
效果:
# 1.BFC 内部的块盒元素依次垂直排列,就是默认情况,因为 html 本身就是 bfc
<style>
.c {
border: 1px solid red;
height: 20px;
}
</style>
<div class="bfc">
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
</div>
# 2. 避免外边距折叠
<style>
.a {
background-color: red;
height: 20px;
}
.b {
background-color: blue;
height: 50px;
overflow: auto;
#生成bfc,与外部隔离;
}
.inner {
margin: 10px 0;
background-color: pink;
height: 10px;
}
</style>
<div class="a"></div>
<div class="b">
<div class="inner"></div>
</div>
# 3.bfc 元素的的左边 margin-box 与包含块的左边 border box 相接触
<style>
.box {
height: 20px;
border: 1px solid black;
margin-left: 200px; // 不会超出
}
.left {
float: left;
height: 20px;
width: 20px;
border: 1px solid red;
margin-left: 20px;
}
</style>
<div class="box">
<div class="left"></div>
</div>
# 4.float 元素不会和 bfc 元素重叠
<style>
.box1 {
height: 40px;
border: 1px solid black;
}
.float {
width: 40px;
height: 20px;
float: left;
background-color: yellow;
}
.bfc1 {
width: 20px;
height: 40px;
background-color: blue;
overflow: auto; // 不然会重叠,跑到黄色浮动元素下面
}
</style>
<div class="box1">
<div class="float"></div>
<div class="bfc1"></div>
</div>
# 5.bfc 可以防止容器塌陷
<style>
.bfc {
overflow: auto;
border: 1px solid black;
}
.float {
width: 40px;
height: 20px;
float: left;
background-color: yellow;
}
</style>
<div class="bfc">
<div class="float"></div>
</div>