直接看代码
- html:
<div class="main">
<div class="content"></div>
</div>
- css
body{
margin:0;
padding:0;
}
.main{
width:200px;
height:200px;
background:tomato;
}
.content{
margin-top: 30px;
width:100px;
height:100px;
background:skyblue;
}
原图
给子元素设置margin-top: 30px之后:
-
原理
一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠。 -
解决方案
1.为父div设置border,我为父div设置border-top:1px solid tomato,理论上还得让父元素高度减去1px;
2.为父div设置padding-top:1px,理论上还得让父元素高度减去1px;
3.为父div设置overflow: hidden;(推荐使用这个)