什么是BFC
BFC的全称是Block Formatting Context,格式化上下文,它是css中一个隐藏的属性,可以为一个元素开启BFC,简单来说它是一块独立的渲染区域,有自己的渲染规则。
如何开启BFC
- display 为以下其中之一的值 inline-block,table-cell,table-caption。
- 浮动元素,float 除 none 以外的值。
- 定位元素,position(absolute,fixed)。
- overflow 除了 visible 以外的值(hidden,auto,scroll)。
- 根元素(html),body元素
BFC渲染规则
- 内部的Box会在垂直方向上一个接一个的放置。
- 属于同一个BFC的两个相邻Box的margin会发生折叠,不同BFC不会发生折叠。
- 每个元素的左外边距与包含块的左边界相接触(从左向右),即使浮动元素也是如此。
- BFC的区域不会与float的元素区域重叠。
- 计算BFC的高度时,浮动子元素也参与计算。
BFC的应用
- 根据
计算BFC的高度时,浮动子元素也参与计算
可以清除浮动。
// 没有清除浮动,高度会塌陷
<style>
.container{
width:300px;
border:solid 1px black;
}
.child-one,.chil-two{
float:left;
width:100px;
height:100px;
background:yellow;
}
.child-two{
background:green;
}
</style>
<div class="container">
<div class="child-one">one</div>
<div class="child-two">two</div>
</div>
如下图所示:
// 利用BFC清除浮动,高度会塌陷
<style>
.container{
width:300px;
border:solid 1px black;
overflow:hidden; // 或者float:left;
}
.child-one,.chil-two{
float:left;
width:100px;
height:100px;
background:yellow;
}
.child-two{
background:green;
}
</style>
<div class="container">
<div class="child-one">one</div>
<div class="child-two">two</div>
</div>
如下图所示:
- 根据
BFC的区域不会与float的元素区域重叠
可以实现两列布局(一个宽度固定,另一个自适应)
<style>
.container{
width: 100%;
}
.child-one{
float:left;
width:100px;
height:400px;
background:yellow;
}
.child-two{
background:green;
height:400px;
overflow: hidden;
}
</style>
<div class="container">
<div class="child-one">one</div>
<div class="child-two">two</div>
</div>
- 根据
属于同一个BFC的两个相邻Box的margin会发生折叠,不同BFC不会发生折叠
可以解决margin重叠的问题。 1、情况一:兄弟元素
// margin会重叠
.child-one{
width: 100px;
height:100px;
background:yellow;
margin-bottom: 20px;
}
.child-two{
width: 100px;
height:100px;
background:green;
margin-top:20px;
}
<div class="child-one">one</div>
<div class="child-two">two</div>
// margin不会重叠(方式一)
.child-one{
width: 100px;
height:100px;
background:yellow;
margin-bottom: 20px;
display: inline-block;
}
.child-two{
width: 100px;
height:100px;
background:green;
margin-top:20px;
}
<div class="child-one">one</div>
<div class="child-two">two</div>
// margin不会重叠(方式二)
.child-one{
width: 100px;
height:100px;
background:yellow;
margin-bottom: 20px;
}
.child-two-wrap{
overflow: hidden;
}
.child-two{
width: 100px;
height:100px;
background:green;
margin-top:20px;
}
<div class="child-one">one</div>
<div class="child-two-wrap">
<div class="child-two">two</div>
</div>
如下图:
2、情况二:父子元素
// margin会传递
.parent{
width: 200px;
height:200px;
background:yellow;
}
.child{
width:100px;
height:100px;
background:green;
margin-top:30px;
}
<div class="parent">
<div class="child">child</div>
</div>
如下图:
// margin不会传递
.parent{
width: 200px;
height:200px;
background:yellow;
overflow:hidden; // 或者 border:solid 1px black;
}
.child{
width:100px;
height:100px;
background:green;
margin-top:30px;
}
<div class="parent">
<div class="child">child</div>
</div>
如下图: