BFC-块级格式化上下文

Alt text


一、定义

BFC:英文名 block formatting context,中文名块级格式化上下文。

二、布局规则

  • BFC的区域不会与float的元素区域重叠
  • 计算BFC的高度时,浮动子元素也参与计算
  • box垂直排列,垂直方向的margin会发生重叠

三、创建BFC

  • float属性不为none
  • overflow不为visible
  • position为absolute或fixed
  • display为inlin-block
  • 最常用overflow : hidden 因为它不会引起布局变化

四、解决问题

(一)两栏布局

1.创建两栏布局时出现的问题

Alt text

2.利用原理

BFC的区域不会与float的元素区域重叠

3.CSS

1
2
3
4
5
.right{
height: 300px;
background: #22AAE3;
overflow: hidden; /*这里为右边的盒子创建了BFC*/
}

4.效果

Alt text

(二)清除浮动

1.由于子元素浮动造成的高度坍塌问题

Alt text

2.利用原理

算BFC的高度时,浮动子元素也参与计算

3.Html

1
2
3
4
<div class="box">
<div class="d1"></div>
<div class="d2"></div>
</div>

4.CSS

1
2
3
.box{
overflow: hidden; /*这里为外层盒子创建了BFC*/
}

5.效果

Alt text

(三)外边距重叠

1.外边距重叠的问题

Alt text

2.利用原理

在同一个BFC内 Box垂直排列,垂直方向的margin会发生重叠,不属于同一个BFC的盒子垂直方向上不会发生重叠

3.HTML

1
2
3
4
5
6
<div class="top_wrap">
<div class="top"></div>
</div>
<div class="bottom_wrap">
<div class="bottom"></div>
</div>

4.CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.top{
width: 150px;
height: 150px;
background: #fc7299;
margin-bottom: 50px;
}
.bottom{
height: 150px;
width: 150px;
background: #22AAE3;
margin-top: 50px;
}
.top_wrap{
overflow: hidden; /*为包裹容器创建BFC*/
}
.bottom_wrap{
overflow: hidden; /*为包裹容器创建BFC*/
}

5.效果

Alt text