我们在随便给一个div加margin-top的时候会给父元素起作用。类似的margin-left就不会。
栗子:
html
<div class=box>
<div class="son"></div>
</div>
css
.box{
width:200px;
height: 200px;
background: lightsalmon;
}
.son{
width:100px;
height: 100px;
background: lightblue;
margin-left:50px;
margin-top: 50px;
}
产生的结果就是
原因是
一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其文档流中的第一个子元素的上边距重叠。
解决方法
方法一、给父元素的样式加 overflow=hidden
.box{
width:200px;
height: 200px;
background: lightsalmon;
overflow: hidden;
}
方法二
.box{
width:200px;
height: 200px;
background: lightsalmon;
padding: 1px;
}
方法三
.box{
width:200px;
height: 200px;
background: lightsalmon;
border: 1px solid white;
}
效果