css防止边距重叠的方法

来源:互联网 发布:我的战争预告片知乎 编辑:程序博客网 时间:2024/06/13 02:49


1.今天整理了一下防止margin击穿的几种方法

先假设一组dom结构

<div class="parent">
<div class="child">
</div>
</div>

通常情况下,如果给子元素设置margin,就会产生这个属性对父元素也产生了同样的效果,然而

这其实不是我们想要的结果,我们只想对子元素设置margin,那么现在我们应该怎么做呢?

(1) 给父元素设置边框

.parent {

width: 300px;       

height: 300px;

border: 1px solid #ccc;

}

.child {

width: 200px;

height: 200px;

margin: 20px;

}

(2)给父元素添加padding

.parent {

padding: 1px;

width: 300px;

height: 300px;

}

.child {

width: 200px;

height: 200px;

margin: 20px;

}

(3)在子元素上方加一个有宽高的兄弟元素,记住是有宽高的。
<div class="parent">
     <div style="width: 20px;height: 20px;margin-top: "></div>
     <div class="child">
     </div>
</div>

(4)给父元素设置 overflow: hidden; 属性
.parent {
overflow: hidden;
width: 300px;
        height: 300px;
}

.child {

width: 200px;

height: 200px;

margin: 20px;

}


(5)给子元素设置 display: inline-block;(如果子元素是行内元素或者行内块级元素则不会产生边距重叠的问题)


.parent {
width: 300px;
        height: 300px;

.child {
width: 200px;

height: 200px;

margin: 20px; 

display: inline-block;

}
(6)使子元素脱离文档流这个实现的方法有很多,浮动,绝对定位等,这里我就不做具体的解释了。
希望可以能帮助到需要的人,如果你觉得这个文章帮到你了,就麻烦动动小手点个赞吧!嘿嘿


原创粉丝点击