一、BFC是什么?
BFC:block formatting context 块状格式化上下文
理解:BFC元素可以理解成被隔离的区间(BFC的子元素不会对外面的元素产生影响);
二、BFC如何触发?
如何让一个元素变成BFC,触发规则如下:
-
float:left | right
-
overflow:hidden | scroll | auto; (不是visible)
-
display:inline-block | table-cell | table-caption | flex | grid ;( 非none 非inline 非block)
-
position: absolute | fiexed ;( 非relative)
三、BFC能解决什么问题?
BFC能解决:
- margin 重合问题
- margin 塌陷问题
- 高度塌陷问题
margin 重合问题
.div1 {
margin-bottom: 20px;
width: 100px;
height: 100px;
background-color: red;
}
.div2 {
margin-top: 20px;
width: 100px;
height: 100px;
background-color: blue;
}
<div class="div1"></div>
<div class="div1"></div>
会出现这样问题,导致上下两个div的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>BFC</title>
<style>
/* margin重合问题 */
.container {
overflow: hidden;//将它变成BFC
}
.div1 {
margin-bottom: 20px;
width: 100px;
height: 100px;
background-color: red;
}
.div2 {
margin-top: 20px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="container">
<div class="div1"></div>
</div>
<div class="container">
<div class="div2"></div>
</div>
</body>
</html>
margin 塌陷问题
.box {
width: 100px;
height: 100px;
background-color: pink;
}
.box1 {
width: 40px;
height: 40px;
margin-top: 50px;
background-color: lightgreen;
}
<div class="box">
<div class="box1"></div>
</div>
以上代码出现的问题:父元素margin-top:50px,子元素没有margin-top,造成margin塌陷
解决方案:
根据触发规则,将box变成BFC元素,添加overflow: hidden或其他
.box {
width: 100px;
height: 100px;
overflow: hidden;
/* float: left; */
/* display: flex; */
background-color: pink;
}
高度塌陷问题
.father {
width: 100px;
background-color: lightseagreen;
}
.child1{
width: 40px;
height: 40px;
float: left;
background-color: red;
}
.child2{
width: 40px;
height: 40px;
float: left;
background-color: pink;
}
<div class="father">
<div class="child1"></div>
<div class="child2"></div>
</div>
以上代码会出现的问题:父元素没有了高度
解决方案:将父元素变成BFC(添加overflow: hidden等)
.father {
width: 100px;
overflow: hidden;
background-color: lightseagreen;
}