
<style>
.box {
width: 100px;
height: 220px;
border: 1px solid pink;
}
.box1 {
width: 100%;
height: 100px;
background-color: purple;
margin-bottom: 5px;
}
.box2 {
width: 100%;
height: 100px;
background-color: blue;
margin-top: 20px;
}
style>
head>
<body>
<div class="box">
<div class="box1">div>
<div class="box2">div>
div>
body>
当上下相邻的两个块级元素(兄弟关系)相遇时,如果上面的元素有下外边距 margin-bottom,下面的元素有上外边距 margin-top,则它们之间的垂直间距不是margin-bottom和margin-top之和。而是取两个值中的较大者。

解决方案:
尽量只给一个盒子添加margin值。

<style>
.father {
width: 200px;
height: 220px;
background-color: pink;
margin-top: 20px;
}
.child {
width: 100px;
height: 100px;
background-color: purple;
margin-bottom: 5px;
margin-top: 40px;
}
style>
head>
<body>
<div class="father">
<div class="child">div>
div>
body>
对于两个嵌套关系(父子关系)的块级元素,父元素有上外边距,同时子元素也有上外边距,此时父元素会塌陷较大的外边距值。
解决方案:
(1)可以为父元素定义上边框。
(2)可以为父元素定义上内边距。
(3)可以为父元素添加 overflow:hidden。
<style>
.father {
width: 200px;
height: 220px;
background-color: pink;
margin-top: 20px;
/* border-top: 1px solid black; */
/* padding-top: 1px; */
overflow: hidden;
}
.child {
width: 100px;
height: 100px;
background-color: purple;
margin-bottom: 5px;
margin-top: 40px;
}
style>
head>
<body>
<div class="father">
<div class="child">div>
div>
body>
