芒果团子的博客

BFC的理解与应用

字数统计: 440阅读时长: 1 min
2018/10/19 Share

BFC的含义

Block Formatting Context ,块级格式化上下文。独立的块级渲染区域,只有block-level box参与,拥有一套渲染规则来约束块级盒子的布局,与区域外部无关。

BFC生成

满足下列条件之一:

  1. 根元素或其它包含它的元素,
  2. 浮动的元素,float为left/right
  3. overflow的值不为visible,auto/scroll/hidden
  4. position:absolute/fixed
  5. display的值为inline-block、table-cell、table-caption、flex,flow-root(chrome及火狐支持,兼容性较差)

布局规则

  1. 元素在垂直方向从上至下排列。
  2. 元素垂直方向的距离由margin决定,两个相邻盒子的margin可能发生重叠
  3. 每个元素的左外边距与包含块的左边界相接触,不会超出它的包含块
  4. BFC区域不会与float元素区域重叠
  5. 计算BFC的高度时,浮动子元素也参与计算
  6. 容器里的子元素不会影响到外面的元素

应用

1.margin重叠:

1
2
3
4
5
6
7
8
9
10
11
12
<<style>
p{
margin: 10px 0;
}
</style>
<div class="box">
<p>p1</p>
<div style="overflow:hidden;">
<p>p2</p>
</div>
<p>p3</p>
</div>

2.子元素浮动,父元素高度塌陷:

1
2
3
4
5
6
7
8
9
10
11
12
13
<style>
.wrap{
overflow:hidden;
}
.float{
float:left;
}
</style>
<div class="wrap">
<div class="float">
我是个浮动的子元素
</div>
</div>

3.浮动元素覆盖在文档流元素上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<style>
.wrap1{
float: left;
width: 100px;
height: 100px;
background-color: pink;
}
.wrap2{
width:200px;
height:200px;
background-color: skyblue;
overflow: hidden;
}
</style>
<div class="wrap1">
wrap1
</div>
<div class="wrap2">
wrap2
</div>

引申应用:创建两栏自适应布局

CATALOG
  1. 1. BFC的含义
  2. 2. BFC生成
  3. 3. 布局规则
  4. 4. 应用