1. 上下位置的兄弟元素
当两个兄弟元素有上下关系时,上面的元素的下内边距 ( margin-bottom )和下面的元素的上内边距 ( margin-top ) 不是简单相加的关系,而是两者之间去最大值;
.father {
width: 400px;
border: 1px solid #000;
}
.box-1 {
width: 200px;
height: 200px;
background-color: blue;
margin-bottom: 60px;
}
.box-2 {
width: 200px;
height: 200px;
background-color: red;
margin-top: 70px;
}
<div class="father">
<div class="box-1">123</div>
<div class="box-2"></div>
</div>
在上面的例子中,正常理解中,两个 div 的间距应该为 60 + 70 = 130px;但是实际上却是 70px。
解决方法:
- 只给一个元素设置边距(像是废话、、、)
- 给两个元素都设置 float: left / right ,使其脱离文档流
- 给两个元素都设置 display: inline-block ,使其不再是块状元素
2. 父子关系的元素
.father2 {
width: 400px;
height: 400px;
background-color: #eee;
margin-top: 100px;
}
.father2 .box-1 {
width: 200px;
height: 200px;
background-color: red;
margin-top: 120px;
}
<div class="father2">
<div class="box-1">123</div>
</div>
上面的例子中,当父子关系的元素同时设置的上内边距 ( margin-top ) 时,也许预想的是父元素对外部元素有 100px 的间隔,然后子元素对父元素有 120px 的间隔。
但是实际情况是父子元素的 margin-top 的值取大的那个生效在外部,即子元素仍然贴合这父元素。
解决方法:
- 想要实现上述的效果可以给父元素设置 margin-top: 100px 和 padding-bottom: 120px,子元素不设置 margin-top
- 给父元素设置 border-top;
- 使元素脱离文档流 ( float / position)