问题描述:当为子盒子设置margin时,并没有将父盒子top撑开,而是子盒子与父盒子的top重合。其实这是因为margin传递问题产生的,且只会出现在嵌套结构中,只有margin-top才会有传递问题。
html
<div id="box1">
<div id="box2"></div>
</div>
css
#box1{
width: 200px;
height: 200px;
background: #ffa0df;
box-sizing: border-box;
}
#box2{
width: 100px;
height: 100px;
background: #96ff38;
margin: 50px;
}
预期效果
塌陷效果
解决方法
方法一:不给子盒子添加margin,而是为父盒子添加padding
css
#box1{
width: 100px;
height: 100px;
background: #ffa0df;
box-sizing: border-box;
padding-top: 20px;
}
#box2{
width: 50px;
height: 50px;
background: #96ff38;
/*margin-top: 20px;*/
}
效果图
方法二:为父盒子添加边框
css
#box1{
width: 100px;
height: 100px;
background: #ffa0df;
box-sizing: border-box;
border:1px solid black;
}
#box2{
width: 50px;
height: 50px;
background: #96ff38;
margin-top: 20px;
}
方法三:给父盒子添加overflow: hidden;
方法四:给父盒子添加display: table;
方法五:给父盒子添加position: fixed;
如果有错误或着不好的地方,请联系我修改。如果觉得对你有用,就点个赞吧,谢谢。