BFC
BFC是什么?
BFC(Blocking Formatting Context),块级格式化上下文。
是一个独立的渲染区域,或者说是一个隔离的独立容器。
形成BFC的条件
- 浮动元素,
float不为none - 绝对定位元素,
position:absolute,position:fixed) display为:inline-block,flex,flow-rootoverflow不为visible- 根元素
html
特性
- 内部box会在垂直方向上一个接一个放置
- 垂直方向上的距离由margin决定
- bfc的区域不会与float的元素区域重叠
- 计算bfc的高度时,浮动元素也参与计算
- 容器里面的子元素不会影响外面元素
使用场景
- 避免margin重叠
- 排除外部浮动
- 清除浮动
切实体会
案例1:阻止外边距重叠
我们在body标签中创建三个div盒子,样式如下:
<style>
.box{
width: 100px;
height: 100px;
background-color: pink;
border: 1px solid black;
margin: 50px;
}
</style>
<body>
<div class="box">我是一个盒子</div>
<div class="box">我是一个盒子</div>
<div class="box">我是一个盒子</div>
</body>
我们看看页面:
因为html根元素本身是一个BFC容器,所以内部的盒子满足BFC特性:
- 内部盒子在垂直方向上一个接一个放置
- 在一个BFC中,两个相邻的块级盒子的垂直外边距会产生重叠
为了不让相邻盒子的外边距重叠,我们可以将这个盒子包裹在一个新的BFC容器中,将其隔离起来:
<style>
.box {
width: 100px;
height: 100px;
background-color: pink;
border: 1px solid black;
margin: 50px;
}
.newbfc {
overflow: hidden;
}
</style>
<body>
<div class="newbfc">
<div class="box">我是一个盒子</div>
</div>
<div class="box">我是一个盒子</div>
<div class="box">我是一个盒子</div>
</body>
我们看看页面:
可以看到包裹在BFC容器中的盒子的margin不再重叠
案例2:排除外部浮动
我们在body标签中创建两个div盒子,一个设置为浮动盒子,一个仅为普通盒子:
<style>
.floatbox {
float: left;
width: 100px;
height: 200px;
border: 1px solid black;
}
.normalbox {
width: 500px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div class="floatbox">我是一个浮动盒子</div>
<div class="normalbox">我是一个普通盒子</div>
</body>
我们看看页面:
为此我们可以将普通盒子变成一个BFC容器,来排除外部浮动
<style>
.floatbox {
float: left;
width: 100px;
height: 200px;
border: 1px solid black;
}
.normalbox {
width: 200px;
height: 100px;
background-color: yellow;
}
.newbfc{
overflow: hidden;
}
</style>
<body>
<div class="floatbox">我是一个浮动盒子</div>
<div class="normalbox newbfc">我是一个普通盒子</div>
</body>
案例3:包含内部浮动
我们在body标签中创建两个盒子,一个外部盒子和一个内部盒子,内部盒子放在外部盒子里:
<style>
.outer-box{
width: 200px;
background-color: pink;
}
.inner-box{
width: 100px;
height: 200px;
float: left;
border: 1px solid black;
}
</style>
<body>
<div class="outer-box">
<div class="inner-box">我是内部浮动盒子</div>
我是外部盒子
</div>
</body>
我们看看页面:
为了让外部盒子能够包含浮动盒子,我们可以将外部盒子变为BFC容器
<style>
.outer-box{
width: 200px;
background-color: pink;
}
.inner-box{
width: 100px;
height: 200px;
float: left;
border: 1px solid black;
}
.newbfc{
overflow: hidden;
}
</style>
<body>
<div class="outer-box newbfc">
<div class="inner-box">我是内部浮动盒子</div>
我是外部盒子
</div>
</body>
我们看看页面: