BFC详细解读-margin重叠问题

456 阅读2分钟

前言

在聊到清除浮动问题时我们用到BFC容器,有许多小伙伴对于BFC容器的了解不深,这里就来浅聊一下BFC到底是啥

BFC是什么

全称:block formatting context(块级格式上下文)

可以理解一个容器有自己的一个环境,比如在一个div中放了几个容器,那么就是在这个div中形成了文档流。所以,BFC是CSS渲染的一部分,主要决定盒子的布局和浮动相互影响的一个区域

创建BFC

创建BFC的方式有很多,我总结了一些可以设置创建BFC的一些属性:

1. 浮动(float:left, float:right)
2. overflow:auto | hidden | scroll | overlay
3. display:inline-block
4. 网格布局(grid | inline-grid)
5. 表格布局(table | inline-table |table-cell | table-caption)
6. 弹性布局 (flex | inline-flex)
7. 定位 (absolute | fixed)

BFC的特点

1. BFC 维护一个常规的文档流
2. BFC 容器计算高度时,会将浮动元素的高度也计算在内
3. BFC 可以解决子容器和父容器的 margin 重叠问题

第二种特征也是BFC容器可以解决浮动导致的父容器高度塌陷问题的原因

这里来详细解释一下第三种特征,也是比较常见的margin重叠问题

margin重叠

margin重叠即外边距重叠

例:在一个 div 容器中放入两个子容器,父容器为绿色背景,子容器分别是红色和蓝色,也给整个 body 设置背景灰色更加直观

<style>
    *{
        margin: 0;
        padding: 0;
        background: #bebebe;/*灰色*/
    }
    .box{
        height: 350px;
        background: #2ae627;/*绿色*/
    }
    .top{
        height: 100px;
        background: #ee522b;/*红色*/
    }
    .bottom{
        height: 100px;
        background: #3883da;/*蓝色*/
    }
    </style>
<body>
    <div class="box">
        <div class="top"></div>
        <div class="bottom"></div>
    </div>
</body>

image.png

当给子容器都设置margin-top:50px;会发现top容器并未和父容器有上边距,而且父容器下移了 50px ,可以理解为父容器因为top容器的上外边距而塌陷,也就是margin重叠问题

        .top{
            height: 100px;
            background: #ee522b;
            margin-top: 50px;
        }
        .bottom{
            height: 100px;
            background: #3883da;
            margin-top: 50px;
        }

image.png

而给父容器添加创建BFC容器的属性 overflow: auto; 后,父容器高度不再塌陷,且 top 容器与父容器正常存在上边距,也就是父容器变成BFC后解决了margin塌陷问题

        .box{
            height: 350px;
            background: #2ae627;
            overflow: auto;
        }

image.png

再给 top 容器添加下外边距margin-bottom:50px;会发现 top 容器的下外边距和 bottom 容器的上外边距仍然重叠,所以BFC只能解决子容器与父容器的重叠问题

image.png

注:正常情况下,容器与容器之间不存在左右margin重叠,只会出现上下 margin 重叠

将两个子容器设置成行内块级容器,同行显示,并调整宽度和添加外边距50px,可以看到左右子容器margin未重叠

    <style>
        *{
            margin: 0;
            padding: 0;
            background: #bebebe;
        }
        .box{
            height: 350px;
            background: #2ae627;
        }
        .top{
            height: 100px;
            width: 20%;
            background: #ee522b;
            display: inline-block;
            margin: 50px;
        }
        .bottom{
            height: 100px;
            width: 20%;
            background: #3883da;
            display: inline-block;
            margin: 50px;
        }
    </style>
    <body>
        <div class="box">
            <div class="top"></div>
            <div class="bottom"></div>
        </div>
    </body>

image.png

在面试中也可能遇到margin重叠问题,希望这些内容对大家有所帮助