0
点赞
收藏
分享

微信扫一扫

嵌套块元素外边距合并导致的塌陷问题

云竹文斋 2022-01-08 阅读 86
csshtmlhtml5

 一.外边距合并

当一个元素包含在另一个元素中时(假设没有内边距或边框把外边距分隔开),它们的上或下外边距也会发生合并。 

接下来看一下这个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>外边距合并的塌陷</title>
</head>
<style>
    .box{
        background: blueviolet;
        width: 300px;
        height: 300px;
    }
    .in-box1{
        background: red;
        width: 200px;
        height: 200px;
        margin-top: 100px;
    }
    .in-box2{
        background: blue;
        width: 100px;
        height: 100px;
        margin-top: 50px;
    }
</style>
<body>
    <div class="box">
        <div class="in-box1">
            <div class="in-box2"></div>
        </div>
    </div>
</body>
</html>

运行代码会发现出现以下结果:

 

这是因为紫色块外边距为0,红色为100px,蓝色为50px,三者最大为100px,所以合并为100px,这和我们预期的效果不符,那么如何来解决这种情况呢有以下三种方法。

二.解决办法

第一种:利用border

为父元素添加上边框,将css中的代码改为如下模样:

<style>
    .box{
        background: blueviolet;
        width: 300px;
        height: 300px;
        margin-top: 0;
        border-top: 1px solid blueviolet;
    }
    .in-box1{
        background: red;
        width: 200px;
        height: 200px;
        margin-top: 100px;
        border-top: 1px solid red;
    }
    .in-box2{
        background: blue;
        width: 100px;
        height: 100px;
        margin-top: 50px;
    }
</style>

第二种:  利用padding

为父元素添加内边距

<style>
    .box{
        background: blueviolet;
        width: 300px;
        height: 300px;
        margin-top: 0;
        /* border-top: 1px solid blueviolet; */
        padding: 1px;
    }
    .in-box1{
        background: red;
        width: 200px;
        height: 200px;
        margin-top: 100px;
        /* border-top: 1px solid red; */
        padding: 1px;
    }
    .in-box2{
        background: blue;
        width: 100px;
        height: 100px;
        margin-top: 50px;
    }
</style>

第三种:利用overflow:hidden

为父元素设置overflow:hidden

<style>
    .box{
        background: blueviolet;
        width: 300px;
        height: 300px;
        margin-top: 0;
        overflow: hidden;
        /* border-top: 1px solid blueviolet;
        padding: 1px; */
    }
    .in-box1{
        background: red;
        width: 200px;
        height: 200px;
        margin-top: 100px;
        overflow: hidden;
        /* border-top: 1px solid red;
        padding: 1px; */
    }
    .in-box2{
        background: blue;
        width: 100px;
        height: 100px;
        margin-top: 50px;
    }
</style>

 结果如下:

 问题解决啦!

举报

相关推荐

0 条评论