当一个div嵌套了另一个div时,父盒子设置了外边距,如:margin-top:50px;内部的子盒子也设置一个外边距margin-top:100px时,会发现子元素并没有如预期所想,与父盒子有个边距。反而父盒子与相领的盒子的margin取了2者的最大值。
如下所示:
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
</div>
**预期:**父盒子距离顶部50px,第一个子盒子距离父盒子的上边框100px,距离第二个子盒子bottom+top,希望是150px。
.father {
margin-top: 50px;
background-color: pink;
width: 200px;
height: 300px;
}
.son1 {
margin-top: 100px;
margin-bottom: 50px;
background-color: yellow;
width: 50px;
height: 50px;
}
.son2 {
margin-top: 100px;
background-color: green;
width: 50px;
height: 50px;
}
实际上:
第一个子盒子距离上边框100px,同时也带着父盒子也距离上边框100px。
第二个子盒子距离上一个是100px,不是预期的150px。
解决
1.父元素添加overflow:hidden;
.father {
margin-top: 50px;
background-color: pink;
width: 200px;
height: 300px;
overflow: hidden;
}
2.父元素添加border
.father {
margin-top: 50px;
background-color: pink;
width: 200px;
height: 300px;
border-top: 1px solid transparent;
}
3.父元素添加padding
.father {
padding-top: 1px;
margin-top: 50px;
background-color: pink;
width: 200px;
height: 300px;
}