【CSS古話今說】-- 01.神奇的CSS-BFC在實戰中的應用

文章首發於掘金css

BFC(Block Formatting Context)是Web頁面中盒模型佈局的CSS渲染模式。它的定位體系屬於常規文檔流

想要實現一個BFC佈局須要知足如下條件之一:

一、float的值不是none。
二、position的值不是static或者relative。
三、display的值是inline-block、table-cell、flex、table-caption或者inline-flex
四、overflow的值不是visiblehtml

想要建立一個BFC有不少方式,可是一些方式可能會帶來其餘的麻煩,例如overflow:scroll等,因此使用的時候仍是要注意一下,本文統一使用overflow:hidden來建立BFC。

1. bfc區域不會與float box 重疊

<style>
        body {
            width: 300px;
            position: relative;
        }

        .aside {
            width: 100px;
            height: 150px;
            float: left;
            background: #666666;
        }

        .main {
            height: 200px;
            background: #fcc;
        }
    </style>
<body>
    <div class="aside"></div>
    <div class="main"></div>
</body>

image.png
若是咱們想要的效果是兩個盒子分開,那麼咱們能夠利用BFC的佈局規則:BFC區域不會與float box重疊的原則,咱們給main加上overflow:hidden的屬性,神奇的事情發生了:
image.pngweb

2. 計算bfc高度的時候,浮動元素也參與計算

<style>
        body {
            width: 500px;
        }

        .par {
            border: 5px solid #fcc;
            /* 下面幾種方式都會生成bfc */
            /* overflow: hidden; */
            /* display: inline-block; */
            /* position: absolute; */
            /* float: left; */
        }

        .child {
            border: 5px solid #f66;
            width: 100px;
            height: 100px;
            float: left;
        }

    </style>

image.png

上述代碼由於浮動,會出現par高度塌陷的狀況,爲了達到清除內部浮動,咱們能夠觸發par生成bfc,那麼par在計算高度的時候,par內部的浮動元素child也會參與計算,因此咱們給par加上overflow:hidden的屬性後問題就解決了。
image.pngide

3. 屬於同一個bfc的兩個相鄰box的margin會發生重疊

<style>
    p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        margin: 100px;
    }
</style>

<body>
        <p>haha</p>
        <p>hehe</p>
</body>

image.png
正常咱們給兩個p 標籤都加上了margin:100px,可是兩個p之間只有100px,爲何呢,同一個BFC環境時候,重疊的margin只去最大的,因此若是想解決這個問題,咱們能夠把下面的p標籤包一層BFC。佈局

<style>
 p {
        color: #f55;
        background: #fcc;
        width: 200px;
        line-height: 100px;
        margin: 100px;
    }
  .warp {
            overflow: hidden;
        }
    </style>
    <p>haha</p>
    <div class="warp">
        <p>hehe</p>
    </div>

總結BFC的三種特性

  1. bfc區域不會與float box 重疊
  2. 計算bfc高度的時候,浮動元素也參與計算
  3. 屬於同一個bfc的兩個相鄰box的margin會發生重疊
相關文章
相關標籤/搜索