什么是margin-top塌陷
若要使子元素距离父元素顶部有一定距离,如果只给子元素设置margin-top属性,结果发现父元素顶部出现位移,子元素相对父元素没位移,这就是margin-top导致的塌陷。
.fatherplus{
width: 600px;
height: 600px;
border:1px solid #333;
.father{
width: 400px;
height: 400px;
background-color: #005CDD;
.son{
width: 200px;
height: 200px;
margin-top: 20px;
background-color: skyblue;
}
}
}
<div className="fatherplus">
<div className="father">
<div className="son"></div>
</div>
</div>

解决方法
-
父元素 溢出隐藏
overflow:hidden; -
父元素 display设为table
display:table; -
父元素 变成行内块元素
display:inline-block; -
父元素 固定定位
position: fixed; -
父元素 绝对定位
position:absolute; -
父元素 添加透明border
border:1px solid transparent; -
父元素 设置padding
padding:1px; -
父元素 浮动
float: left; -
推荐写法父元素 添加伪元素&::before{ content:''; display:table; }
总结
推荐给父元素添加伪元素,因为其他写法都可能会影响页面布局。
最终效果


500

被折叠的 条评论
为什么被折叠?



