Box
是CSS
布局的对象和基本单位, 直观点来说,就是一个页面是由很多个Box
组成的。元素的类型和display
属性,决定了这个Box
的类型。 不同类型的 Box
, 会参与不同的Formatting Context
(一个决定如何渲染文档的容器),因此Box
内的元素会以不同的方式渲染。让我们看看有哪些盒子:
-
block-level box
:display
属性为block
,list-item
,table
的元素,会生成block-level box
。并且参与block fomatting context
; -
inline-level box
:display
属性为inline
,inline-block
,inline-table
的元素,会生成inline-level box
。并且参与inline formatting context
; -
run-in box
: 根据上下文决定对象是内联对象还是块级对象。
Formatting context
是W3C CSS2.1
规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。最常见的Formatting context
有Block fomatting context
(BFC
)和Inline formatting context
(IFC
)。
BFC 定义
BFC
(Block formatting context
)直译为"块级格式化上下文"
。它是一个独立的渲染区域,只有Block-level box
参与, 它规定了内部的Block-level Box
如何布局,并且与这个区域外部毫不相干。
BFC 布局规则
- 内部的
Box
会在垂直方向,一个接一个地放置。 -
Box
垂直方向的距离由margin
决定。属于同一个BFC
的两个相邻Box
的margin
会发生重叠。 - 每个元素的
margin box
的左边, 与包含块border box
的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。 -
BFC
的区域不会与float box
重叠。 -
BFC
就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。 - 计算
BFC
的高度时,浮动元素也参与计算。
哪些元素会生成 BFC?
- 根元素;
-
float
的属性不为none
; -
position
为absolute
或者fixed
; -
display
为inline-block
,table-cell
,table-caption
,flex
,inline-flex
; -
overflow
不为visible
。
BFC 的作用和原理
清除内部浮动
<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
的高度时,浮动元素也参与计算。
.par {
overflow: hidden;
}
防止垂直 margin 重叠
<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
重叠。
Box
垂直方向的距离由margin
决定。属于同一个BFC
的两个相邻Box
的margin
会发生重叠。
我们可以在p
外面包裹一层容器,并触发该容器生成一个BFC
。那么两个P
便不属于同一个BFC
,就不会发生margin
重叠了。
<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>
自适应两栏布局
<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>
每个元素的margin box
的左边, 与包含块border box
的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。
BFC
的区域不会与float box
重叠。
我们可以通过通过触发main
生成BFC
, 来实现自适应两栏布局。
.main {
overflow: hidden;
}
原文链接
http://www.cnblogs.com/lhb25/p/inside-block-formatting-ontext.html
https://www.cnblogs.com/CafeMing/p/6252286.html