对于两个嵌套关系的块级元素,如果父元素没有上边距或边框,父元素的上外边距会与子元素的上外边距发生合并情况(塌陷)。
<style>
.father{
width:500px;
height:500px;
background-color:hotpink;
}
.son{
width:200px;
height:200px;
background-color:pink;
margin-top:30px;
}
</style>
<div class="father">
<div class="son">
</div>
</div>
像上面的div块级元素嵌套,当给子元素添加上外边距margin值时,父元素也会被子元素“带跑”,距上边距30px。
解决方案:
- 为父元素添加上边框 border-top;
- 为父元素添加上内边距 padding-top;
- 为父元素添加overflow:hidden;
第三种方法用的最多,也建议用第三种方法。