CSS實戰筆記(九) BFC

1、基本介紹

BFC(Block Formatting Context)的中文名稱是塊級格式化上下文,它是一個獨立渲染的區域

在這個區域的內部有自己的佈局規則,內部的元素對外部的元素沒有任何影響,反之亦然

2、佈局規則

BFC 的內部元素都必須是塊級盒子,並且這些盒子有一定的佈局規則,具體如下:

  • 盒子在垂直方向上一個接着一個放置
  • 相鄰盒子在垂直方向上的距離由 margin 決定,屬於同一個 BFC 的兩個相鄰盒子會發生 margin 重疊的情況
  • 每個盒子的左外邊距與容器的左邊界相接觸,即使它是浮動盒子也是如此
  • BFC 的區域不會與浮動盒子重疊
  • BFC 的高度計算要包含浮動盒子

3、創建方式

創建一個 BFC 的方法有很多,下面來介紹比較常用的幾種:

  • 根元素本來就是一個 BFC
  • 設置 float 屬性的值不爲 none
  • 設置 overflow 屬性的值不爲 visible
  • 設置 position 屬性的值爲 absolutefixed
  • 設置 display 屬性的值爲 flow-rootinline-boxflex

4、應用實例

(1)解決高度塌陷的問題

如果我們沒有顯式設置父元素的高度,並將子元素設置爲浮動的,那麼父元素就會出現高度塌陷

<!DOCTYPE html>
<html>
<head>
    <style>
        .father {
            border: 1px solid red;
            width: 300px;
        }
        .son {
            border: 1px solid blue;
            width: 100px;
            height: 80px;
            float: left;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>

在這裏插入圖片描述

清除浮動,意思就是清除由於子元素浮動導致父元素高度塌陷的影響,清除浮動有兩個基本的思路

  • 在父元素的最後加一個冗餘元素,並給這個元素設置 clear:both
.father {
    border: 1px solid red;
    width: 300px;
}
.father::after { /* 關鍵 */
    content: '';
    display: table;
    clear: both;
}
.son {
    border: 1px solid blue;
    width: 100px;
    height: 80px;
    float: left;
}
  • 將父元素設置爲 BFC,因爲 BFC 的高度計算要包含浮動元素
.father {
    border: 1px solid red;
    width: 300px;
    display: flow-root; /* 關鍵 */
}
.son {
    border: 1px solid blue;
    width: 100px;
    height: 80px;
    float: left;
}

在這裏插入圖片描述

(2)解決外邊距塌陷的問題

屬於同一個 BFC 的兩個相鄰盒子會發生外邊距塌陷的情況

<!DOCTYPE html>
<html>
<head>
    <style>
        .elder-brother {
            width: 100px;
            height: 80px;
            border: 1px solid red;
            margin-bottom: 10px;
        }
        .little-brother {
            width: 100px;
            height: 80px;
            border: 1px solid blue;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="elder-brother"></div>
    <div class="little-brother"></div>
</body>
</html>

在這裏插入圖片描述

解決方法就是給其中一個元素包一個 BFC,這樣就能使得兩個元素不在同一個 BFC 中

<!DOCTYPE html>
<html>
<head>
    <style>
        .elder-brother {
            width: 100px;
            height: 80px;
            border: 1px solid red;
            margin-bottom: 10px;
        }
        .wrapper {  /* 關鍵 */
            display: flow-root;
        }
        .little-brother {
            width: 100px;
            height: 80px;
            border: 1px solid blue;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="elder-brother"></div>
    <div class="wrapper"><div class="little-brother"></div></div>
</body>
</html>

在這裏插入圖片描述

【 閱讀更多 CSS 系列文章,請看 CSS學習筆記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章