外边距折叠问题

2023-07-25  本文已影响0人  姜治宇

折叠外边距的大小,等于相邻边距中的最大值。

<!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>Document</title>
    <style>
        .t1{
            width:100%;
            height:20px;
            margin-bottom:10px;
            background:red;
        }
        .t2{
            width:100%;
            height:20px;
            margin-top:10px;
            background:blue;
        }

    </style>
</head>
<body>
    <div class="t1"></div>
    <div class="t2"></div>
</body>
</html>
1.png

可以看到,上下两个margin都是10px,按理叠加应该是20px,但实际是10px。
这种情况还好,但多个容器会存在多外边距折叠的问题。

<!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>Document</title>
    <style>
        .t1{
            width:100%;
            height:20px;
            margin-bottom:10px;
            background:red;
        }
        .t2{
            width:100%;
            
            margin-top:10px;
          
        }
        .t3{
            width:100%;
            height:20px;
            
            margin-top:20px;
            background:blue;
        }
    </style>
</head>
<body>
    <div class="t1"></div>
    <div class="t2">
        <div class="t3"></div>
    </div>
</body>
</html>
2.png

t3容器的margin-top为20px,居然跟外部的10px折叠了,取大值就是20px。
我们其实想要的是,这个margin-top为20px,只留在t2中,而不跟外部折叠。怎么办呢?

解决方案

1、对容器使用overflow:auto(非visible即可)。
2、在两个外边距之间加上边框border、或内边距padding。
3、浮动元素、内联块。
4、绝对定位或固定定位。
5、flex弹性布局。

上一篇 下一篇

猜你喜欢

热点阅读