1. margin塌陷
我们先来看个现象,需求是:在父子元素中,通过marigin让父元素相对左边及顶部各距离100px,也让子元素相对于父元素左边和顶部各50px。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin塌陷</title>
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(231, 73, 107);
margin-left: 100px;
margin-top: 100px;
}
.son{
width: 100px;
height: 100px;
background-color: rgb(43, 236, 194);
margin-left: 50px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果如下
一句话总结:父子嵌套的元素垂直方向的margin取最大值。
但是有的时候我们不希望有这样的问题,那我们如何解决margin塌陷的问题呢
可以通过触发BFC来解决(如果你还不了解BFC可以点击链接https://www.jianshu.com/p/f996a41912e0)
如下通过overflow: hidden触发bfc ,即可
<style>
.father{
width: 200px;
height: 200px;
background-color: rgb(231, 73, 107);
margin-left: 100px;
margin-top: 100px;
overflow: hidden;/* 触发bfc */
}
.son{
width: 100px;
height: 100px;
background-color: rgb(43, 236, 194);
margin-left: 50px;
margin-top: 50px;
}
</style>
结果如下:
理想的结果
解决!
2. margin合并
还是来先看一个需求,把两个兄弟块元素,一个设置下外边距100px,一个设置上外边距100px,让两个元素相距200px。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin合并</title>
<style>
.one{
background-color: pink;
height: 20px;
margin-bottom: 100px;
}
.two{
background-color: purple;
height: 20px;
margin-top: 100px;
}
</style>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
</html>
结果如下:
我们发现这两个元素之间,他们的margin-bottom和margin-top合并了,并且显示的是较大值。
同样我们可以用bfc来解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>margin合并</title>
<style>
.one {
background-color: pink;
height: 20px;
margin-bottom: 100px;
}
.two {
background-color: purple;
height: 20px;
margin-top: 100px;
}
.wrap{
/* 触发bfc */
overflow: hidden;
}
</style>
</head>
<body>
<!-- 这里有更改结构哦 -->
<div class="one"></div>
<div class="wrap">
<div class="two"></div>
</div>
</body>
</html>
结果
解决问题!但是一般不这么解决,为什么?因为margin合并和margin塌陷不一样,margin塌陷只添加了CSS,margin合并除了添加CSS,还修改了HTML结构。我们知道一般html结构是不能乱改动的,所以我们通过数学计算来解决这各margin合并的问题。比如上面的例子,我们只要设置前面元素的margin-bottom为200px或者后面元素的margin-top为200px即可。