上下两个盒子边距合并问题

    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        div {
            width: 100px;
            height: 100px;
        }

        .top {
            background-color: red;
            margin-bottom: 20px;
        }

        .bottom {
            background-color: blue;
            margin-top: 10px;
        }
    </style>
    <div class="top"></div>
    <div class="bottom"></div>

效果如下
css边距合并的问题-小白菜博客
可以看到下面蓝色的外边距被上面的取代了,不是我们想象的那样 20+10 而是 20

结论:上下两个兄弟盒子的margin都为正取大,都为负取小,一正一负相加
注意:只有普通文档流中块框的垂直外边距才会发生外边距合并。

父子边距问题

<style>
        .father {
            width: 200px;
            height: 200px;
            background-color: red;
            /* overflow: auto; */
        }

        /* .father::before {
            display: table;
            content: "";
        } */

        .son {
            width: 50px;
            height: 50px;
            background-color: blue;
            margin-top: 10px;
        }
    </style>
    <div class="father">
        <div class="son"></div>
    </div>

效果如下
css边距合并的问题-小白菜博客
我们想象的结果是son这个盒子距离父盒子father顶部10px,但实际效果却father距离顶部10px。

这是因为父盒子没有设置外边距,边框,内边距 。当父盒子设置了这三者之一,都不会出现这样的效果

如果不想设置外边距,边框,内边距 又想到达同样的效果,可以这样做:

父元素{
	overflow:auto;
}
/*或者*/
父元素::before{
  display: table;
  content: "";
}

改正后:

    <style>
        .father {
            width: 200px;
            height: 200px;
            background-color: red;
            overflow: auto;
        }

        /* .father::before {
            display: table;
            content: "";
        } */

        .son {
            width: 50px;
            height: 50px;
            background-color: blue;
            margin-top: 10px;
        }
    </style>
    <div class="father">
        <div class="son"></div>
    </div>

效果如下
css边距合并的问题-小白菜博客
注意:只有普通文档流中块框的垂直外边距才会发生外边距合并。