什么是BFC
BFC直译为块级格式化上下文,它是一个独立的渲染区域,只有Block-level box参与,它规定了内部Block-level Box如何布局,并且与这个区域外部毫不相干;
Block-level box:display 属性为 block, list-item, table 的元素,会生成 block-level box
BFC的规矩规则
1. BFC里面的box都会以垂直方向排列
2. 同一个BFC里面中相邻的两个盒子的外边距会重叠
3. 每个元素的左margin box的左边与包含块的border box的左边相接触(对于从左往右的格式,否则相反),即使存在浮动也一样
4. BFC的区域不会和float Box重叠
5. BFC就是一个独立的容器,容器里面的元素不会影响到外面的元素,反之也如此
BFC的生成
1. 根元素
2. float属性不为none;
3. display属性为:line-block,table-cell,line-flex,flex
4. position属性不为:static,relative;
5. overflow属性不为:visible;
BFC的案例运用
1.外边距的合并
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 100px;
height: 100px;
margin: 50px;
background-color: #ff8000;
}
.box2 {
width: 100px;
height: 100px;
margin: 50px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
display:inline-block;就可以完美解决这个问题
2. 两栏自适应布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 100px;
height: 100px;
float: left;
background-color: #ff8000;
}
.box2 {
width: 200px;
height: 200px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
代码效果
overflow:hidden就可以解决这个问题;
3. 最后一个案例,BFC里面的元素不会影响外面的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 100px;
height: 100px;
background-color: #ff8000;
}
.box2 {
width: 200px;
height: 200px;
background-color: #ff0000;
}
.son {
width: 100px;
height: 100px;
background: #000;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2">
<div class="son"></div>
</div>
</body>
</html>
代码效果
margin-top:-50px会发生什么情况?
margin-top:-50px属性就会发现,红色盒子(box2)和橙色盒子(box)在页面的布局改变了,红色盒子(box2)覆盖了橙色盒子(box1);但是我们想让黑色盒子盒子添加margin-top:-50px属性,页面布局不发生改变,怎么做呢?
我们只需要让红色盒子产生一个新的BFC区域就可以了;