1.相邻元素外边距合并
<!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>
div {
height: 80px;
width: 280px;
border: black dotted 2px;
padding: 35px;
text-align: center;
font-weight: bolder;
}
.box1 {
margin-top: 30px;
margin-bottom: 30px;
background-color: green;
}
.box2 {
margin-top: 90px;
background-color: red;
}
</style>
</head>
<body>
<div class="box1">盒子one</div>
<div class="box2">盒子two</div>
</body>
</html>
2.父子(嵌套)元素外边距合并
<!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>
#dad {
height: 400px;
width: 400px;
background-color: purple;
margin-top: 30px;
}
#son {
height: 200px;
width: 200px;
background-color: green;
margin-top: 120px;
}
</style>
</head>
<body>
<div id="dad">
<div id="son">子元素内容</div>
</div>
</body>
</html>
son选择器中的margin-top: 120px;这一步: 让子元素盒子有120px的外边距,与父元素盒子顶部分离开,但是会发生父元素塌陷,即父元素margin-top值会增加120px(父元素盒子会在之前margin-top=30px的基础上再下移120px),而子元素在盒子中的位置没有改变,对子元素的margin-top操作无效。
如何解决父元素塌陷问题,以下有三种供参考:
(1)给父元素定义边框border
(2)给父元素定义内边距padding
(3)给父元素添加overflow:hidden