BFC定义
块级格式化上下文,它是指一个独立的块级渲染区域,只有 Blosk-level BOX 参与,该区域拥有一套渲染规则来约束块级盒子的布局,且与区域外部无关。
从一个现象说起
- 一个盒子不设置 height ,当内容都浮动时无法撑起自身
- 这个盒子就没有形成 BFC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>父盒子没有高度</title>
<style>
.son {
width: 300px;
height: 300px;
background-color: #ccc;
float: left;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
</div>
</body>
</html>
如何创建 BFC
- float 的值不是 none
- position 的值不是 static 或者 relative
- display 的值是 inline-block 、 flex 、 inline-flex
- overflow:hidden
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>创建BFC</title>
<style>
.father {
/* float: left; */
/* position: absolute; */
/* display: inline-block; */
overflow: hidden;
}
.son {
width: 300px;
height: 300px;
background-color: #ccc;
float: left;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
</div>
</body>
</html>
BFC 的其他作用
- 取消盒子的 margin 塌陷
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin 塌陷</title>
<style>
.father {
width: 200px;
height: 300px;
background-color: #aaa;
overflow: hidden; /* 不加这个属性的话,会把父盒子带下来 20px */
}
.son {
width: 100px;
height: 100px;
background-color: #ccc;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
- 阻止元素被浮动元素覆盖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>阻止覆盖</title>
<style>
.son {
width: 100px;
height: 100px;
background-color: #ccc;
float: left;
}
.son-last {
width: 100px;
height: 200px;
background-color: #aaa;
overflow: hidden; /* 不加这个属性的话,该盒子会被浮动的 son 盒子给盖住*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
<div class="son"></div>
<div class="son-last"></div>
</div>
</body>
</html>