Loading

垂直外边距重叠问题

垂直外边距折叠

垂直外边距折叠的发生

兄弟元素之间(对开发有利,无需处理)

当两个盒子(兄弟元素)处于垂直状态时,相邻两个外边距不是相加,而是取最大值

<style>
    .box1,
    .box2{
        width: 200px;
        height: 200px;
    }

    .box1{
        background-color: #bfa;
        margin-bottom: 100px;

        /* 
            margin-bottom: -200px;
            兄弟元素相邻的外边距一正一负会相加
            -200px + 200px = 0px
         */
    }

    .box2{
        background-color: orange;
        margin-top: 200px;
    }

    /* 相邻的外边距不是100px + 200px = 300px
        而是取最大值也就是200px
    */
</style>
<body>
    <!-- 两个盒子处于垂直状态 兄弟元素 -->
    <div class="box1"></div>
    <div class="box2"></div>
</body>

父子元素之间(需要解决)

当两个元素是父子关系时,子元素的外边距(父元素的外边距)会传递给对方

<!-- 父子元素 -->
<div class="outer">
    <div class="inner"></div>
</div>
<style>
.outer{
    width: 200px;
    height: 200px;
    background-color: #bfa;
}

.inner{
    width: 100px;
    height: 100px;
    background-color: orange;
    /* 父子元素外边距重叠:子元素的外边距(父元素的外边距)会传递给对方 */
    margin-top: 30px;
}
</style>
<body>
<div class="outer">
    <div class="inner"></div>
</div>
</body>

解决方法1: 使用文字破坏外边距相邻

<div class="outer">
    破坏相邻状态
    <div class="inner"></div>
</div>

缺点: 需要增加html结构

解决方法2: 使用border破坏外边距相邻

<style>
.outer{
    width: 200px;
    height: 199px;  /* 200px - 1px需要维持可见框大小 */
    background-color: #bfa;

    /* 使用border破坏外边距相邻状态 */
    border-top: solid 1px red;

}

.inner{
    width: 100px;
    height: 100px;
    background-color: orange;
    /* 父子元素外边距重叠:子元素的外边距(父元素的外边距)会传递给对方 */
    margin-top: 50px;
}
</style>

缺点: 需要维持可见框大小

解决方法3: 不是用外边距,转而去调整内边距(padding)

<style>
.outer{
    width: 200px;
    height: 170px;  /* 200px - 30px需要维持可见框大小 */
    background-color: #bfa;
    padding-top: 30px;
}

.inner{
    width: 100px;
    height: 100px;
    background-color: orange;
    /* 父子元素外边距重叠:子元素的外边距(父元素的外边距)会传递给对方 */
    /* margin-top: 30px; */
}
</style>

缺点: 需要维持可见框大小

终极版:解决方法: clearfix类封装

/* 解决外边距重叠 */
.clearfix::before{
    /* 由于必须使用margin,所以解决思路是破坏两个margin相邻的状态 */
    content: '';
    /* 使用table的好处:
            -   既能将虚拟元素变成块元素
            -   同时在内容为空时,不占据空间(block会占据) 
    */
    display: table;
}
posted @ 2021-02-10 23:31  虚伪渲染敷衍  阅读(235)  评论(0编辑  收藏  举报