# BFC

# BFC是什么

BFC(Block Formatting Context)格式化上下文,是Web页面中盒模型布局的CSS渲染模式,指一个独立的渲染区域或者说是一个隔离的独立容器。

# 形成BFC的条件

  • 1、浮动元素,float 除 none 以外的值;

  • 2、定位元素,position(absolute,fixed);

  • 3、display 为以下其中之一的值 inline-block,table-cell,table-caption;

  • 4、overflow 除了 visible 以外的值(hidden,auto,scroll);

# BFC特性

  • 1.内部的Box会在垂直方向上一个接一个的放置。

  • 2.垂直方向上的距离由margin决定。

  • 3.bfc的区域不会与float的元素区域重叠。

  • 4.计算bfc的高度时,浮动元素也参与计算。

  • 5.bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素。

# 特性解读

# 特性2和5

根据特性2和5,我们可以解决外边距折叠的问题(外边距会在垂直方向上以较大的边距为准,而不是相邻边距相加),

解决这个问题,我们可以将折叠边距的某个元素至于一个BFC容器中,使其与外界隔离,从而达到相邻边距不折叠的效果。

<div class="content">
  <div class="warp">
    <div class="box1"></div>
  </div>
  <div class="box2"></div>
</div>
1
2
3
4
5
6

 







 














.content{
  overflow: hidden;
  background-color: aqua;
  width: 200px;
  height: 200px;
}

/* 将box1至于warp中,warp触发BFC,与外界隔离 */
.warp{
  overflow: hidden;
}

.box1 {
  height: 50px;
  margin: 10px 0;
  background-color: yellow;
}

.box2 {
  height: 50px;
  margin: 20px 0;
  background-color: yellow;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

bfc1

# 特性3

我们都知道一个元素设置浮动了之后会脱离文档流,可能会浮动在其他元素的上部,参考如下代码:

<div class="content">
  <div class="left">left</div>
  <div class="right">right</div>
</div>
1
2
3
4
.left {
  float: left;
  width: 100px;
  height: 200px;
  background-color: aqua;
}
.right {
  height: 400px;
  background-color: blanchedalmond;
}
1
2
3
4
5
6
7
8
9
10

bfc2

根据特性3、bfc的区域不会与float的元素区域重叠,我们可以设置right元素快为BFC区域,使其无法与left区域重叠


 




.right {
  overflow: hidden;
  height: 400px;
  background-color: blanchedalmond;
}
1
2
3
4
5

bfc3

# 特性4

我们都知道,当内层元素浮动时,会导致内层元素高度塌陷,代码效果如下:

<div class="content">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
1
2
3
4
5
6
.content{
  background-color: blueviolet;
  padding: 20px;
}
.box{
  width: 50px;
  height:100px;
  float: left;
  background-color: blanchedalmond;
  margin-right: 20px;
}
1
2
3
4
5
6
7
8
9
10
11

bfc4

此时,为了能让父元素的高度被撑开,我们可以让父元素触发BFC,从而将浮动元素的高度也计算在父级高度内



 



.content{
  background-color: blueviolet;
  overflow: hidden;
  padding: 10px;
}
1
2
3
4
5

bfc5

上次更新: 6/1/2020, 7:13:47 PM