CSS中,margin-top和margin-botttom有一些特殊性。它们会在某种情况之间相互合并,并且会将值最大的那个当作外边距的值。
1. margin-top具有继承性
当两个盒子是父子关系时,对父元素设置margin-top,子元素也相当于有了相同的margin-top。
.box1 {
margin-top: 20px;
width: 200px;
height: 200px;
background-color: #000000;
}
.box2 {
width: 100px;
height: 100px;
background-color: #0000FF;
}
<div class="box1">
<div class="box2"></div>
</div>
2.margin-top,margin-bottom会合并
当两个盒子是父子关系或者上下兄弟关系时,设置margin-top,margin-bottom。两个盒子之间的margin-top,margin-bottom会合并,取最大的值当作共同的外边距。
// 上述CSS代码修改
.box2 {
margin-top: 30px;
width: 100px;
height: 100px;
background-color: #0000FF;
}
如图:两个盒子margin-top合并成为一个,子元素的较大,所以最终的外边距以子元素的为准。
.box1 {
margin-bottom: 60px;
width: 200px;
height: 200px;
background-color: #000000;
}
.box2 {
margin-top: 30px;
width: 100px;
height: 100px;
background-color: #0000FF;
}
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
如图:当两个盒子为上下兄弟关系时,下边盒子的margin-top和上边盒子的margin-bottom会合并,上边的外边距比较大,所以最终外边距为上盒子的margin-bottom
3.margin-top,margin-bottom“不”会合并
有时候,当使用弹性布局时,上下兄弟盒子的外边距不会合并。
.box {
display: flex;
flex-direction: column;
}
.box1 {
margin-bottom: 60px;
width: 200px;
height: 200px;
background-color: #000000;
}
.box2 {
margin-top: 30px;
width: 100px;
height: 100px;
background-color: #0000FF;
}
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
如图:两个兄弟盒子之间的外边距,为上盒子margin-bottom和下盒子margin-top之和。margin-top和margin-bottom没有合并。