css外边距合并问题(外边距塌陷)

1.父子元素之间的外边距margin合并问题(外边距塌陷)

<!-- 结构 -->
<div class="box">
    <div class="b1"></div>
</div>
<!-- 样式 -->
.box {
            width: 800px;
            height: 500px;
            background-color: orange;
        }

        .b1 {
            margin-top: 20px;
            width: 200px;
            height: 200px;
            background-color: purple;
        }

 

我们想要的效果是这样的

但实际是这样的

解决方法:

  父元素添加代码段:
              /*border: 1px solid transparent; !*方法1*!*/
            /*float: left; !*方法2*!*/
            /*position: absolute; !*方法3*!*/
            /*padding: 1px; !*方法4*!*/
            /*display: inline-block; !*方法5*!*/
            /*overflow: hidden; !*方法6*!*/
            /*overflow: auto; !*方法7*!*/            

 

2.兄弟元素之间的外边距合并问题

<!--结构-->
<div class="box1">
    <div class="b2"></div>
    <div class="b3"></div>
</div>

<!--样式-->
.b2,
.b3 {
width: 100px;
height: 100px;
border: 1px solid #ccc;
}

.b2 { background-color: pink; margin-bottom: 20px; } /* b2 margin-bottom 20px; b3 margin-top 30px ;本应该b2 和 b3 间隔50px */ /* 实际 只有 30px 因为外边距margin发生了合并 */ .b3 { margin-top: 30px; background-color: green; }

我们想要的效果:粉色 和 绿色间隔为50px

但实际是这样的:间隔只有 30px 因为margin发生了合并 合并后就只剩margin值较大的部分

解决方法:

<!--增加左浮动 或 转换为行内块-->
 /*float: left; !* 1.设置左浮动 解决外边距margin 合并问题呢*! */
    /*display: inline-block; !*2.转换为行内块 解决外边距margin 合并问题*!*/

 

posted @ 2019-07-14 15:03  码小龙  阅读(2581)  评论(0编辑  收藏  举报