BFC的理解运用(CSS)

ps:实用性几乎为零,但架不住面试时候问啊

BFC的理解

块级格式化上下文。它是指一个独立的块级渲染区域,只有Block-level BOX(块级盒子参与)参与, 该区域拥有套渲染规则来约束块级盒子的布局,且与区域外部无关

从一个现象开始说起

一个盒子不设置height,当内容子元素都浮动时,无法撑起自身。

那么就可以说这个盒子没有形成BFC

如何创建BFC

方法①: float的值不是none

方法②: pos ition的值不是stat ic或者relative

方法③: disp Lay的值是inline- block、flex或者 inline-flex

方法④: overflow: hidden;

 <style>
        .father {
            /* float: left; */
            /* position: absolute; */
            /* display: inline-block; */
            /* 最优 */
            overflow: hidden; 
        }

        .son {
            width: 300px;
            height: 300px;
            background-color: blue;
            float: left;
        }
 </style>
 <body>
    <div class=" father">
        <div class="son"></div>
        <div class=" son"></div>
        <div class=" son"></div>
    </div>
</body>
复制代码

BFC的其他作用

BFC可以取消盒子margin場陷

margin塌陷:给子盒子设施margin时候,会带着父盒子一起走,从而达不到想要的效果

    <style>
        .father {
            width: 200px;
            height: 300px;
            background-color: pink;
            //避免盒子塌陷
            overflow: hidden;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: blue;
            margin-top: 20px;
        }
    </style>
<body>
    <div class=" father">
        <div class="son"></div>
    </div>
</body>
复制代码

BFC可以可以阻止元素被浮动元素覆盖

这个还要解释吗?浮动元素瞎跑的现象

 <style>
        .son {
            width: 100px;
            height: 100px;
            background-color: blue;
            float: left;
        }

        .son-last {
            width: 200px;
            height: 300px;
            background-color: red;
            overflow: hidden;
        }
    </style>
      <div>
        <div class="son"></div>
        <div class="son"></div>
        <div class="son-last"></div>
    </div>

复制代码

**简而言之,bfc能让盒子自己做自己的主,不被外界轻易改变。茅坑的臭石头
**

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享