布局时margin会影响父元素

时间:2023-12-12 22:36:02

布局时margin会影响父元素.md

在布局使用margin时

<div class=”login-bg”>
<div class=”login”>
12345
</div>
</div> <style>

.login-bg{

background-color:red;

width: 400px;

height: 400px;

margin: 0 auto;

background: url(imac.png) no-repeat;

background-size:400px 400px;

}

.login{

background-color: #999;

width: 300px;

height: 200px;

margin-top: 100px;

}

</style>

此时两个div都与上偏移了100px;

而不是我们所想要的.login偏移100px;

解决方法

给 login-bg Div 加上 padding/border,

或者给 login-bg Div / Inner Div 设置为 float/position:absolute(CSS2.1规定浮动元素和绝对定位元素不参与Margin折叠)