margin塌陷和margin合并问题及解决方案

7,105 阅读2分钟

margin 塌陷问题

一个父盒子里面套了一个小盒子,如果这个父盒子里面没有文字,也没有边框(border),也没有padding-top (这三个条件中没有一个满足的),当我们给小盒子设置margin-top的时候,会发现父盒子会跟着一起往下掉,这个现象就叫做margin值穿透。

先举个例子:

<style>
        *{
            margin: 0;
            padding: 0;
        }
         body{
            background-color:#000;
        }
        .box{
            width: 100px;
            height: 100px;
            background: lightcoral;
        }
        .box1{
            width: 50px;
            height: 50px;
            margin-top:50px;
            background: lightblue;
        }

原理:

父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margi会取其中最大的值

正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位.但由于margin的塌陷,父级相对浏览器定位.而子级没有相对父级定位,子级相对父级,就像坍塌了一样.

margin塌陷解决方法

1.给父级设置边框或内边距(不建议使用)

.box{
        width: 100px;
        height: 100px;
        background: lightcoral;
        border: 1px solid #000;
    }

2.触发bfc(块级格式上下文),改变父级的渲染规则

改变父级的渲染规则有以下四种方法,给父级盒子添加

(1)position:absolute/fixed

(2)display:inline-block;

(3)float:left/right;

(4)overflow:hidden;

这四种方法都能触发bfc,但是使用的时候都会带来不同的麻烦,具体使用中还需根据具体情况选择没有影响的来解决margin塌陷

margin合并

有两个盒子,它们是上下关系,当我们给上面的盒子设置margin-bottom:value1; 又给下面的盒子设置了margin-top:value2; 那它俩直接的距离并不是距离之和,而是选择最大的那个距离。

<style>
        *{
            margin: 0;
            padding: 0;
        }
        html{
            background: #000;

        }
        .box{
            width: 100px;
            height: 100px;
            background: lightcoral;
            margin-bottom: 20px;
        }
        .box1{
            width: 100px;
            height: 100px;
            margin-top:50px;
            background: lightblue;
            margin-top:50px;
        }
        /* limegreen lightsalmon lightslategray */
    </style>
</head>
<body>
    <div class="box"></div>
    <div class="box1"></div>
</body>

margin合并问题也可以用bfc解决;

1.给box2加上一层父级元素并加上overflow:hidden;

2.给两个都加一层父级再加bfc

<div>
    <div class="box1"></div>
</div>
<div>
    <div class="box2"></div>
</div>

但是这两种方法都改变了HTML结构,在开发中是不能采用的

所以在实际应用时,在margin合并这个问题上,我们一般不用bfc,而是通过只设置上面的元素的margin-bottom来解决距离的问题