什么是 BFC
Block Formatting Contexts(BFC):塊級(jí)元素格式化上下文
BFC布局規(guī)則
- 內(nèi)部的Box會(huì)在垂直方向牙瓢,一個(gè)接一個(gè)地放置。
- Box垂直方向的距離由margin決定辜妓。** 屬于同一個(gè)BFC的兩個(gè)相鄰Box的margin會(huì)發(fā)生重疊 **
- 每個(gè)元素的margin box的左邊, 與包含塊border box的左邊相接觸( 對(duì)于從左往右的格式化今豆,否則相反)嫌拣。即使存在浮動(dòng)也是如此。
- BFC的區(qū)域不會(huì)與float box重疊呆躲。
- BFC就是頁面上的一個(gè)隔離的獨(dú)立容器异逐,容器里面的子元素不會(huì)影響到外面的元素。反之也如此插掂。
- 計(jì)算BFC的高度時(shí)灰瞻,浮動(dòng)元素也參與計(jì)算
觸發(fā)BFC的方式(一下任意一條就可以)
- float屬性不為none
- position為absolute或fixed
- display為inline-block, table-cell, table-caption, flex, inline-flex
- overflow不為visible
BFC應(yīng)用場景
1.之前面試的時(shí)候被問到頻率比較高的一道css題就是:寫出幾種實(shí)現(xiàn)一個(gè)div內(nèi)分兩列,左邊一列固定寬度辅甥,右邊一列自適應(yīng)布局的方法酝润,以及每種方法實(shí)現(xiàn)的原理是什么? 其中有一種就可以利用BFC實(shí)現(xiàn)璃弄,代碼如下:
<!DOCTYPE HTML>
<html>
<head>
<style>
.con {
width: 100%;
background-color: #c0c0c0;
position: relative;
box-sizing: border-box;
border: 10px solid #999;
}
.left {
width: 100px;
height: 50px;
float: left;
background: #ff8000;
}
.main {
height: 100px;
overflow: hidden;/*將右邊元素設(shè)置為BFC元素即可*/
background: #ffc68c;
}
</style>
</head>
<body>
<div class="con">
<div class="left"></div>
<div class="main"></div>
</div>
</body>
</html>
右邊不設(shè)置為bfc元素時(shí)的效果如下:
bfc1.jpg
原因就是bfc的這條規(guī)則:
每個(gè)元素的margin box的左邊要销, 與包含塊border box的左邊相接觸(對(duì)于從左往右的格式化,否則相反)夏块。即使存在浮動(dòng)也是如此疏咐。
右邊設(shè)置為BFC元素可以利用BFC的區(qū)域不會(huì)與float box重疊規(guī)則
實(shí)現(xiàn)。效果如下:
bfc2.jpg
2.利用BFC( 計(jì)算BFC的高度時(shí)脐供,浮動(dòng)元素也參與計(jì)算
)輕松清楚內(nèi)部浮動(dòng):
<!DOCTYPE HTML>
<html>
<head>
<style>
.con {
width: 100%;
background-color: #ffffff;
position: relative;
box-sizing: border-box;
border: 1px solid #999;
overflow: hidden;/*使其成為BFC*/
}
.left {
width: 100px;
height: 50px;
float: left;
background: #ff8000;
}
</style>
</head>
<body>
<div class="con">
<div class="left"></div>
<div class="left"></div>
</div>
</body>
</html>