嵌套块元素外边距合并导致的塌陷(3种处理方法)

164 阅读1分钟

一、现象解释

指对于嵌套关系的块元素,若父子双方均有外边距则父元素会塌陷较大的外边距(通俗解释:就是父子均按照最大的外边距进行移动)

image-20220104185252503

tips:谁大塌陷多少

eg:image-20220104183200548

<style>
    
    .father{
        width: 500px;
        height: 500px;
        background-color: rgb(15, 213, 240);
        margin-top: 100px;
    }
    .son{
        width: 300px;
        height: 300px;
        background-color: rgb(14, 71, 226);
        margin-top: 50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">
​
        </div>
    </div>
</body>

二、解决方案

1.加一个透明的边框

即:加一个border: 1px solid transparent;

image-20220104183808400

<style>
    
    .father{
        width: 500px;
        height: 500px;
        background-color: rgb(15, 213, 240);
        margin-top: 100px;
        border: 1px solid transparent;
    }
    .son{
        width: 300px;
        height: 300px;
        background-color: rgb(14, 71, 226);
        margin-top: 50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">
​
        </div>
    </div>
</body>

2.给父元素加一个内边距

即:padding:1px;

image-20220104183808400

<style>
    
    .father{
        width: 500px;
        height: 500px;
        background-color: rgb(15, 213, 240);
        margin-top: 100px;
        padding: 1px;
    }
    .son{
        width: 300px;
        height: 300px;
        background-color: rgb(14, 71, 226);
        margin-top: 50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">
​
        </div>
    </div>
</body>

3.给父元素加一个overflow:hidden;

4.其他