一、什么是BFC?
- BFC 全称为块格式化上下文 (Block Formatting Context)。
- BFC是Web页面的可视化CSS渲染出的一部分。它是块级盒布局出现的区域,也是浮动层元素进行交互的区域。
注:BFC只有功能,没有定义。
二、BFC原理
- 内部的盒子会在垂直方向,一个接一个地放置。
- 盒子垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠(即margin合并)。
eg:如果Box1的margin-bottom为30px;Box2的margin-top为50px;则两个盒子的距离为50px。 - 每个元素的左外边距与包含块的左边界相接触(从左到右),即使浮动元素也是如此。(即BFC中的子元素不会超出它的包含块,而position为absolute的元素可以超出它的包含块边界)。
- BFC的区域不会与float的元素区域重叠。
- 计算BFC的高度时,浮动元素也参与计算。
- BFC是一个独立的区域(容器),容器内的子元素不会影响外面的元素。
三、开启BFC属性的方法
- 根元素
- 浮动元素
- 绝对定位元素
- display的值为 inline-block、table、table-cell、、等表格类元素、flow-root
- overflow的值不为 visible 的元素
四、常见的用BFC解决的问题
1. margin垂直塌陷
解决方法:
- 给父级设置绝对定位:position:absolute
- 给父级设置行级块元素:display:inlinebolck
- 给父级添加溢出隐藏:overflow:hidden
2.外边距合并
( 两个或多个毗邻的普通流中的块元素垂直方向上的 margin 会合并)
如果两个Box之间有外边距合并,给其中的一个盒子外套另一个盒子,使其触发BFC,这样两者处于不同的BFC中,不会相互影响。
代码示例:
.father {
background: pink;
width: 300px;
}
.child1, .child2 {
width: 100px;
height: 100px;
text-align: center;
margin: 100px;
}
.child1 {
background:red;
}
.child2 {
background: blue;
}
.container {
overflow: hidden;
}
//CSS部分
<body>
<div class="father">
<div class="child1">这是一个块</div>
<div class="container"><div class="child2">这是另一个块</div>
</div>
</div>
</body>
//html部分
3.高度塌陷
(父元素内部的子元素脱离文档流,父元素高度塌陷)
仍然是给其中的一个盒子外套另一个盒子,使其触发BFC,这样两者处于不同的BFC中,不会相互影响。
示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用BFC解决高度塌陷问题</title>
<style type="text/css">
.box1 {
border: 5px;
overflow: hidden:
}
.box2 {
width: 200px;
height: 200px;
background-color: yellow;
float: left
}
.box3 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
<div class="box3"></div>
</body>
</html>
4.多栏布局
利用BFC实现自适应的三栏布局。
代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用BFC设置多栏布局</title>
<style type="text/css">
.left{
float: left;
width: 200px;
height: 100px;
background-color: green;
}
.right{
float: right;
width: 200px;
height: 100px;
background-color: pink;
}
.center{
overflow: hidden;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="taxian">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
</body>
</html>
注:center盒子的div一定要在写在最下面,这样左右两边设置左右浮动,不占位,center盒子自动顶上去。