情景1:两个父子关系的块级盒子会出现上外边距塌陷的情况:上外边距为父子中大的那一个。解决办法:为父级盒子添加上内边距/上边框/overflow:hidden,为盒子添加浮动、定位。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.father {
width: 100px;
height: 100px;
margin-top: 20px;
background-color: green;
}
.son {
margin-top: 100px;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
情景2:一个父级盒子包含两个子级盒子则第一个儿子会塌陷,第二个儿子不会出现上外边距塌陷的情况。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.father {
margin-top: 10px;
width: 100px;
height: 100px;
margin-top: 20px;
background-color: green;
}
.son1 {
margin-top: 100px;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: red;
}
.son2 {
margin-top: 200px;
margin-left: 200px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
</body>
</html>