导致边距塌陷的两种情况:
1. 同级元素塌陷
两个同级元素,垂直排列。上面的盒子给了margin-bottom,下面的盒子给了margin-top。那么这两个边距将会重叠,按照大的值来计算。
<!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>
.box1 {
width: 100px;
height: 100px;
background-color: pink;
margin-bottom: 20px;
}
.box2 {
width: 100px;
height: 100px;
background-color: skyblue;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
效果图:
此时两个盒子,box1设置了20px的下边距,box2设置了30px的上边距,但是最终两个盒子之间的边距为30px。
解决办法:不让这两个边距同时出现。
2. 父子元素塌陷
两个父子元素,内部的子盒子给了margin-top,父元素也会受到影响,同时产生上边距,也就是父子粘连。
<!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>
.father {
width: 200px;
height: 200px;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
background-color: skyblue;
margin-top: 30px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
效果图:
此时两个嵌套的父子盒子,给子盒子设置的30px的上边距,导致父元素塌陷
解决方法:
-
给父盒子设置border,添加border后父子盒子就不是真正意义上的贴合了。
-
给父盒子添加overflow:hidden;
-
给父盒子设定padding值
-
给父盒子添加position:fixed;
-
给父子添加diaplay:table;
-
利用伪元素给父元素的前面添加一个空元素