天马3798

嵌套div的margin-top问题

1.代码现象

<div class="rightDownDiv">
<div class="corner cornerOne">
<div class="btnIcon"></div>
</div>
<div class="corner cornerTwo">
<div class="btnIcon"></div>
</div>
</div>

css

.rightDownDiv {
margin: 100px;
border: 1px solid green;
width: 96px;
height: 180px;
}
.rightDownDiv .cornerOne {
background: yellow;
}
.rightDownDiv .cornerTwo {
background: gray;
}
.rightDownDiv .corner {
width: 96px;
height: 70px;
}
.rightDownDiv .btnIcon {
border: 1px solid red;
margin-top: 10px;
width: 50px;
height: 50px;
}

结果:内层div的margin-top ,在外层div中也体现了

原因:嵌套div 的垂直方向的magin会出现折叠

         嵌套div的margin-top问题 - 天马3798 - 天马3798

解决方案1:父元素设置overflow:hidden

.rightDownDiv .corner {
width: 96px;
height: 70px;
overflow:hidden;
}

嵌套div的margin-top问题 - 天马3798 - 天马3798

  解决方案2:父元素设置边框

.rightDownDiv .corner {
width: 96px;
height: 70px;
border:1px solid blue;
}

嵌套div的margin-top问题 - 天马3798 - 天马3798

  解决方案3:子元素浮动float

.rightDownDiv .btnIcon {
border: 1px solid red;
margin-top: 10px;
width: 50px;
height: 50px;
float:left;
}

嵌套div的margin-top问题 - 天马3798 - 天马3798

解决方案4:子元素设置为inline-block

.rightDownDiv .btnIcon {
border: 1px solid red;
margin-top: 10px;
width: 50px;
height: 50px;
display:inline-block;
}

嵌套div的margin-top问题 - 天马3798 - 天马3798

解决方案5:子元素定位:absolute

.rightDownDiv .btnIcon {
border: 1px solid red;
margin-top: 10px;
width: 50px;
height: 50px;
position:absolute;
}

嵌套div的margin-top问题 - 天马3798 - 天马3798

.........等等


评论