BFC 格式化上下文

2018-12-27  本文已影响0人  Haiya_32ef

1 格式化上下文

定义:它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用
常见的有BFC,IFC

2 块级格式化上下文

定义:它是一个独立的渲染区域,只有Block-level box参与, 它规定了内部的Block-level Box如何布局,并且与这个区域外部毫不相干

3 布局规则

4 BFC生成条件

5 BFC的作用及原理

//body里有两个元素,此时aside会遮住main
<style>
    .aside {
        width: 100px;
        height: 150px;
        float: left;
        background: #f66;
    }
    .main {
        height: 200px;
        background: #fcc;
    }
</style>
<body>
    <div class="aside"></div>
    <div class="main"></div>
</body>
效果

根据布局规则第三条:每个元素的margin box的左边, 与包含块border box的左边相接触。所以会形成上诉现象。

为了形成两栏布局。根据布局规则第四条:BFC的区域不会与float box重叠。让main变成BFC即可

.main {
    overflow: hidden;
}

效果如下:


效果

2 清除浮动

<style>
    .par {
        border: 5px solid #fcc;
        width: 300px;
    }
 
    .child {
        border: 5px solid #f66;
        width:100px;
        height: 100px;
        float: left;
    }
</style>
<body>
    <div class="par">
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>
效果

根据BFC布局规则第六条:计算BFC的高度时,浮动元素也参与计算;让par形成BFC即可

.par {
    overflow: hidden;
}
效果

3 防止margin重叠

<style>
    p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        text-align:center;
        margin: 100px;
    }
</style>
<body>
    <p>Haha</p>
    <p>Hehe</p>
</body>
页面

根据BFC布局规则第二条:Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠;让其中一个块形成BFC即可

<style>
    .wrap {
        overflow: hidden;
    }
    p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        text-align:center;
        margin: 100px;
    }
</style>
<body>
    <p>Haha</p>
    <div class="wrap">
        <p>Hehe</p>
    </div>
</body>
效果
上一篇 下一篇

猜你喜欢

热点阅读