再回答这个问题之前,大家先想下我们的文档流的划分方式有哪些?
- 普通流;
- 定位流;
- 浮动流。
1.BFC(block formatting context)-块格式上下文
这解释太官方了,用人话怎说?
开玩笑,简单来说,BFC就是被隔离的区间(BFC的子元素不会对外面的元素产生影响)。
BFC元素 非 BFC 元素 body BFC 元素 float: left | right none overflow hidden | scroll | auto visible position absolute | fixed relative display inline-block | table-cell | flex | inline-flex | grid | table-caption inline、block、
none
2.BFC 能解决什么问题?
(1)防止 margin 重叠
看个例子: 页面上的两个元素,分别设置了 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>Document</title>
<style>
.box {
width: 100px;
height: 100px;
}
.box1 {
background-color: aqua;
margin-bottom: 20px;
}
.box2 {
background-color: brown;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="box box1"></div>
<div class="box box2"></div>
</body>
</html>
浏览器中的显示效果:
BFC如何解决呢?注意“BFC的子元素不会对外面的元素产生影响”这句话,那我们让 box1 和 box2 的父元素都变为 BFC 模块,那么这时候的子元素 box1 所设置的 margin 就不会对外面的元素 box2 产生影响,同理,子元素 box2 所设置的 margin 就不会对外面的元素 box1 产生影响。从而就可以解决 margin 重叠问题。
<div class="container"> <div class="box box1"></div> </div> <div class="container"> <div class="box box2"></div> </div>
.container { overflow: hidden; }
上面使用了 overflow:hidden 方式,大家可以尝试上面表格中的其他方式,但是要注意,有的会改变页面布局方式。
(2)防止 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>Document</title>
<style>
.container {
width: 100px;
height: 100px;
background-color: burlywood;
}
.box {
width: 50px;
height: 50px;
background-color: cadetblue;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
显示:
我们给子元素 box 设置了 margin-top,为什么父元素也下去了?这就是 margin 塌陷问题。
解决方案:给父元素设为 BFC。
.container { width: 100px; height: 100px; background-color: burlywood; display: inline-block; }
方法有很多种,子元素之所以连带父元素一下下移,是因为子元素设置的 margin-top 没有对标,给父元素设置 border-top: 1px solid #333 也是可以的。
显示效果:
(3)高度坍塌(或者说清除浮动)
直接上代码:
<!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>Document</title>
<style>
.box {
width: 100px;
border: 1px solid #000;
background-color: chartreuse;
}
.box1 {
float: left;
width: 100px;
height: 100px;
background-color: chocolate;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
</html>
显示:
大家注意到没,父元素的高度没了。原因是子元素的浮动问题,导致父元素的高度坍塌。解决方案:将父元素 BFC。
.box { width: 100px; border: 1px solid #000; background-color: chartreuse; position: absolute; }
显示: