BFC
BFC(Block Formatting Context)格式化上下文,是Web页面中盒模型布局的CSS渲染模式,指一个独立的渲染区域或者说是一个隔离的独立容器。
BFC 即 Block Formatting Contexts (块级格式化上下文),属于普通流。
可以把 BFC 理解为一个封闭的大箱子,箱子内部的元素无论如何翻江倒海,都不会影响到外部。
一、什么条件下可以让元素产生BFC
- float属性不为none;意思是,只要设置了浮动,当前元素就创建了BFC。
- overflow不为visible,可以让属性是 hidden、auto。【最常用】
- 在定位中,只要posiiton的值不是 static或者是relative即可,可以是absolute或fixed,也就生成了一个BFC。
- display为inline-block,table-cell,table,caption,flex,inline-flex。
二、BFC的特性
1.内部的Box会在垂直方向上一个接一个的放置。
2.垂直方向上的距离由margin决定
3.bfc的区域不会与float的元素区域重叠。
4.计算bfc的高度时,浮动元素也参与计算
5.bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素。 三、应用
三、常用场景
(1) 清除盒子垂直方向上外边距合并
(在常规文档流中,两个兄弟盒子之间的垂直距离是由他们的外边距所决定的,但不是他们的两个外边距之和,而是以较大的为准。)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.father {
background-color: cadetblue;
width: 300px;
}
.son1 {
width: 200px;
height: 200px;
margin-bottom: 100px;
background-color: antiquewhite;
}
.son2 {
width: 200px;
height: 200px;
margin-top: 50px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
</body>
</html>
使用BFC解决外边距合并问题,由于son1 和son2的box属于同一个BFC,会发生margin重叠。所以我们可以设置,两个不同的BFC,也就是我们可以让把第二个div再用一个div包起来,然后激活它使其成为一个BFC代码和效果图如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.father {
background-color: cadetblue;
width: 300px;
}
.son1 {
width: 200px;
height: 200px;
margin-bottom: 100px;
background-color: antiquewhite;
}
.son2 {
width: 200px;
height: 200px;
margin-top: 50px;
background-color: aquamarine;
}
.fa {
overflow: hidden;
}
</style>
</head>
<body>
<div class="father">
<div class="son1"></div>
<div class="fa">
<div class="son2"></div>
</div>
</div>
</body>
</html>
(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></title>
</head>
<style>
.box {
border: 5px solid red;
width: 300px;
}
.box1,.box2 {
border: 5px solid blue;
width:100px;
height: 100px;
float: left;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
给父盒子激活bfc(只需要给父盒子设置 overflow: hidden;),具体代码和效果图如下:
<!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></title>
</head>
<style>
.box {
border: 5px solid red;
width: 300px;
overflow: hidden;
}
.box1,.box2 {
border: 5px solid blue;
width:100px;
height: 100px;
float: left;
}
</style>
<body>
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>