[css]一个块格式化上下文(BFC)阻止外边距重叠的示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .demo{
            height:100px;
            background: #eee;
        }
        .parent{
            height:200px;
            background: #88f;
        }
        .child{
            height:100px;
            margin-top:20px;
            background: #0ff;
            200px;
        }
    </style>
</head>
<body>
    <section class="demo">
        <h2>此部分是能更容易看出让下面的块的margin-top。</h2>
    </section>
    <section class = "parent">
        <article class="child">
            <h2>子元素</h2>
            margin-top:20px;
        </article>
        <h2>父元素</h2>
            没有设置margin-top
    </section>
</body>
</html>

案例:如下图,父元素没有设置margin-top,而子元素设置了margin-top:20px;可以看出,父元素也一起有了边距(因为父元素和子元素的外边距合并了)。

 

 

 

 

解决办法:

.parent{
            height:200px;
            background: #88f;
            overflow: auto;
        }

为parent类添加overflow:auto属性就可以阻止它们的外边距合并,因为此值让父元素创建了块格式化上下文(BFC)进而阻止外边距合并。

*为parent创建边框也可以阻止外边距合并,原因不详

posted @ 2022-09-27 16:02  yiyide266  阅读(21)  评论(0编辑  收藏  举报