BFC规范与浏览器差异

437 阅读1分钟

BFC规范

BFC(Box Formatting Context, **块级格式化上下文**) 是网页上的一个**隔离的独立容器**,容器里面的子元素不会影响到外面的元素,反之亦然。

当一个盒子没有设置height,当内容子元素都浮动时,无法撑起自身,则此盒子没有形成BFC。

如何创建BFC

方法一: float的值不是none;

方法二: position的值不是static或者relative

方法三: display的值是inline-block、flex、或者 inline-flex

方法四: overflow:hidden;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width:200px;
            border: 2px solid #000;
            /* BFC方法一 ,平白无故给标签浮动,此方法相对不太合适*/
            /* float:left; */

            /* 方法三,此方法同样不太合适,将本身是块级元素转换成行内块 */
            /* display:inline-block; */

            /* 方法二 通过绝对定位形成BFC,合适*/
            /* position:absolute; */
            /* 第四种方法,使用overflow:hidden 实现BFC */
            overflow:hidden;
        }
        .box .c1 {
            width:100px;
            height:100px;
            background-color:red;
            float:left;
        }
        .box .c2 {
            float:left;
            width:100px;
            height:100px;
            background-color:orange;
        }
    </style>
</head>
<body>

    <div class="box">
        <div class="c1"></div>
        <div class="c2"></div>
    </div>
</body>
</html>

BFC其他作用

BFC可以取消margin的塌陷

BFC可以阻止元素被浮动的元素覆盖。。。。无现实意义 ,只需记住其能够完场此效果即可

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {
            width:100px;
            height:100px;
            background-color:red;
            margin:50px;
          
        }
        div {
            overflow:hidden;
        }
        .c1 {
            float:left;
            width:200px;
            height:200px;
            background-color:red;
        }
        .c2 {
            /* float:left; */
            /* 在此设置浮动隐藏无现实意义 ,只需记住其能够完场此效果即可*/
            overflow:hidden;

            width:100px;
            height:100px;
            background-color:blue;
        }

    </style>
</head>
<body>
    <div>
        <p></p>
    </div>
    <div>
        <p></p>
    </div>
    <section class="c1"></section>
    <section class="c2"></section>
</body>
</html>

浏览器差异

IE6,7 浏览器使用haslayout机制,和BFC规范略有差异,比如IE浏览器可以使用zoom:1属性“让盒子拥有layout.

如果要制作兼容到IE6,7的网页时,尽量让网页布局变得简单,内部有浮动的盒子要设置height属性,按照规范编程