一.BFC定义
他解决了块级元素如何对它的内容进行布局,以及与其他元素的关系和相互作用
关键词解释:
块级元素:父级(是一个块元素)
内容:子元素(是一个块元素)
其它元素:与内容同级别的兄弟元素
相互作用:BFC里的元素与外面的元素不会发生影响
二.BFC触发方式
- float的值不为none
- overflow的值不为visible
- display的值为table-cell,table-caption或inline-block之一
- position的值不为static或releative中任何一个
- 弹性项:display:flex
- 网格项:display:grid
三.BFC的布局规则
- margin不会传递给父级(父级触发了BFC)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
display: flex;
justify-content: center;
}
.father{
width: 500px;
height: 500px;
background-color: hotpink;
display: flex;
justify-content: center;
}
.son{
width: 300px;
height: 100px;
background-color: deepskyblue;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
</html>
2.非浮动元素不会覆盖浮动元素的位置(非浮动元素触发了BFC)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.first{
width: 300px;
height: 300px;
background-color: hotpink;
float: left;
}
.second{
width: 300px;
height: 300px;
background-color: deepskyblue;
overflow: hidden;
}
</style>
</head>
<body>
<div class="first"></div>
<div class="second"></div>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/f04af9e6a88f8ad3993be42614c323c5.png)
3.两个相邻的元素上下margin不会重叠(其中一个元素添加一个单独的父级,然后让他的父级触发了BFC)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.father{
overflow: hidden;
}
.son{
width: 100px;
height: 100px;
background-color: yellow;
margin-bottom: 50px;
}
.uncle{
width: 100px;
height: 100px;
background-color: deepskyblue;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<div class="uncle">
</div>
</body>
</html>