0x00 嵌套块元素塌陷问题复现
首先是基础代码
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
<style>
.father {
width: 400px;
height: 400px;
background-color: black;
}
.son {
width: 200px;
height: 200px;
background-color: aqua;
}
</style>
然后增加father和son的margin属性
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
<style>
.father {
width: 400px;
height: 400px;
background-color: black;
margin: 50px;
}
.son {
width: 200px;
height: 200px;
background-color: aqua;
margin: 100px;
}
</style>
可以看到这里son块元素margin并没有和预期一样的生效,这种情况称为块元素的塌陷
0x01 解决办法
可以为父元素添加上边框;
可以为父元素定义上内边距;
可以为父元素设置overflow:hidden;
.father {
width: 400px;
height: 400px;
background-color: black;
margin: 50px;
border: 1px solid transparent;
padding-top: 1px;
overflow: hidden;
}
可以看到问题已经完美解决了