转载http://www.cnblogs.com/lhb25/p/inside-block-formatting-ontext.html javascript
在解释 BFC 是什么以前,须要先介绍 Box、Formatting Context的概念。css
Box 是 CSS 布局的对象和基本单位, 直观点来讲,就是一个页面是由不少个 Box 组成的。元素的类型和 display 属性,决定了这个 Box 的类型。 不一样类型的 Box, 会参与不一样的 Formatting Context(一个决定如何渲染文档的容器),所以Box内的元素会以不一样的方式渲染。让咱们看看有哪些盒子:html
Formatting context 是 W3C CSS2.1 规范中的一个概念。它是页面中的一块渲染区域,而且有一套渲染规则,它决定了其子元素将如何定位,以及和其余元素的关系和相互做用。最多见的 Formatting context 有 Block fomatting context (简称BFC)和 Inline formatting context (简称IFC)。java
CSS2.1 中只有 BFC
和 IFC
, CSS3 中还增长了 GFC
和 FFC。
css3
BFC(Block formatting context)直译为"块级格式化上下文"。它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,而且与这个区域外部绝不相干。ide
代码:布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<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>
|
页面:
flex
根据BFC
布局规则第3条:spa
每一个元素的margin box的左边, 与包含块border box的左边相接触(对于从左往右的格式化,不然相反)。即便存在浮动也是如此。3d
所以,虽然存在浮动的元素aslide,但main的左边依然会与包含块的左边相接触。
根据BFC
布局规则第四条:
BFC
的区域不会与float box
重叠。
咱们能够经过经过触发main生成BFC
, 来实现自适应两栏布局。
1
2
3
|
.main {
overflow: hidden;
}
|
当触发main生成BFC
后,这个新的BFC
不会与浮动的aside重叠。所以会根据包含块的宽度,和aside的宽度,自动变窄。效果以下:
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<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
布局规则第六条:
计算
BFC
的高度时,浮动元素也参与计算
为达到清除内部浮动,咱们能够触发par生成BFC
,那么par在计算高度时,par内部的浮动元素child也会参与计算。
代码:
1
2
3
|
.par {
overflow : hidden ;
}
|
效果以下:

代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<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重叠。
根据BFC布局规则第二条:
Box
垂直方向的距离由margin决定。属于同一个BFC
的两个相邻Box
的margin会发生重叠
咱们能够在p外面包裹一层容器,并触发该容器生成一个BFC
。那么两个P便不属于同一个BFC
,就不会发生margin重叠了。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<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>
|
效果以下: