01 BFC官方解释
www.w3.org/TR/CSS2/vis…
大致意思如下
02 什么情况下会形成BFC
MDN解释
developer.mozilla.org/zh-CN/docs/…
03 BFC的作用
大致意思
图解如下
3.1 折叠现象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
width: 400px;
height: 200px;
background-color: orange;
margin-bottom: 30px;
}
.box2 {
width: 300px;
height: 200px;
margin-top: 50px;
background-color: brown;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
3.2 解决折叠
让它们处在不同的BFC中
效果如下
可以看到根本没有解决折叠的现象
这是因为它们还处在同一个BFC中即html根元素的BFC中
修改代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
overflow: hidden;
}
.box1 {
width: 400px;
height: 200px;
background-color: orange;
margin-bottom: 30px;
overflow: hidden;
}
.box2 {
width: 300px;
height: 200px;
margin-top: 50px;
background-color: brown;
}
</style>
</head>
<body>
<div class="container">
<div class="box1"></div>
</div>
<div class="box2"></div>
</body>
</html>
这样box1就处于container的BFC中,box2处于html中的BFC
3.3 BFC解决浮动高度塌陷
3.3.1 常用解决方法清除浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
background-color: orange;
}
.box .item {
float: left;
width: 400px;
height: 200px;
border: 1px solid #000;
background-color: brown;
}
.clear-fix::after {
content: "";
clear: both;
display: block;
visibility: hidden;
height: 0;
}
</style>
</head>
<body>
<div class="box clear-fix">
<div class="item "></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
3.3.2 BFC解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
overflow: hidden;
background-color: orange;
}
.box .item {
float: left;
width: 400px;
height: 200px;
border: 1px solid #000;
background-color: brown;
}
</style>
</head>
<body>
<div class="box">
<div class="item "></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
官方解释