CSS: 兄弟元素,上面div写margin-bottom:20px,下面div写margin-top:20px,会重叠

175 阅读1分钟

希望的结果是40px。

事实的结果是20px,解决方案可以使用BFC 也就是在下面div增加个父元素,

<div class="container">
    <div class="tes">
        1
    </div>
    <div class="bfc">
        <div class="tex">
        2
        </div>
    </div>
</div>

<style>
        *,body,html{
            padding: 0;
            margin: 0;
        }
        .container{
            background: pink;
        }
        .tes{
            width: 100px;
            height: 100px;
            background-color: #fff;
            margin-bottom: 20px;
        }
        .tex{
            width: 100px;
            height: 100px;
            background-color: #b4dbed;
            margin-top: 20px;

        }
        .bfc{
            overflow: hidden;  //重点
        }
    </style>