BFC是css中的塊渲染規(guī)則弄兜,決定了各個元素間的相互作用药蜻,用于處理頁面布局。具有BFC特性的元素就相當(dāng)于一個獨立的容器替饿,與其他元素互不影響语泽。
默認(rèn)這個屬性是關(guān)閉的,如果想打開视卢,需要一些觸發(fā)條件踱卵。
處于BFC區(qū)域的元素具有的特征:
1.在同一個BFC區(qū)域內(nèi)的兩個相鄰元素或者父子元素,它們的垂直外邊距會發(fā)生重疊据过。
2.計算高度時惋砂,會把浮動子元素計算在內(nèi)。
3.此元素變成了一個獨立的元素绳锅,與外界元素不會互相影響西饵。
4.不會被浮動的元素覆蓋。
開啟BFC的條件:
1.body根元素本身是默認(rèn)開啟了BFC鳞芙;
2.設(shè)置元素浮動眷柔,float不為none;
3.設(shè)置定位原朝,position:absolute驯嘱、fixed;
4.設(shè)置display:inline-block喳坠、table-cell鞠评、flex;
5.設(shè)置overflow不為visible(hidden丙笋、auto谢澈、scroll)煌贴。
BFC作用:
1.阻止被浮動的元素覆蓋,可做兩欄布局自適應(yīng)锥忿。
兩個相鄰的元素牛郑,第一個設(shè)置了float后,會覆蓋在第二個元素上面敬鬓,為阻止被覆蓋淹朋,可在第二個元素上設(shè)置float、overflow: hidden钉答、position: absolute础芍、display: inline-block;。
<style>
.two{
width:100px;
height: 100px;
background-color: rgb(18, 150, 36);
float: left;
}
.three{
width: 200px;
height: 200px;
background-color: rgb(201, 24, 24);
float: left;
/* overflow: hidden; */
/*position: absolute;*/
/*display: inline-block;*/
}
</style>
<body>
<div class="one">
<div class="two"></div>
<div class="three"></div>
</div>
</body>
2.解決高度塌陷
子元素設(shè)置浮動后数尿,父元素如果沒設(shè)置高度會出現(xiàn)高度塌陷仑性。可以給父元素設(shè)置overflow: hidden;右蹦、float: left;诊杆、position: absolute;、display: inline-block;何陆,但是使用最多的是overflow: hidden;其它的很少用晨汹。
<style>
.one{
width: 150px;
background-color: rgb(18, 150, 36);
overflow: hidden;
/*float: left;*/
/*position: absolute;*/
/*display: inline-block;*/
}
.two{
width: 100px;
height: 100px;
background-color: rgb(135, 121, 214);
float: left;
}
</style>
<body>
<div class="one">
<div class="two"></div>
</div>
</body>
3.解決相鄰兩塊元素垂直外邊距、父元素與子元素垂直外邊距重疊的問題
垂直外邊距重疊的情況:
(1)相鄰兩元素都設(shè)置了margin贷盲,在垂直方向上淘这,兩元素垂直外邊距不會相加,而是取外邊距最大的值巩剖。
(2)父子關(guān)系的元素铝穷,子元素設(shè)置了margin,在垂直方向上佳魔,子元素的margin會傳給父元素氧骤,使得父元素產(chǎn)生外邊距。
為什么會產(chǎn)生這兩種垂直外邊距的情況吃引?
首先html根元素本身就開啟了BFC,處于html中的元素及其子元素其頂部是相鄰的刽锤,所以會發(fā)生上部垂直外邊距重疊镊尺。
對于相鄰的兄弟元素,它們同處于一個BFC區(qū)域并思,所以垂直外邊距也發(fā)生了重疊庐氮。
<style>
.one{
width: 150px;
background-color: rgb(225, 231, 226);
}
.two{
width: 100px;
height: 100px;
background-color: rgb(135, 121, 214);
margin: 10px 0;
}
.three{
width: 100px;
height: 100px;
background-color: rgb(201, 24, 24);
margin: 10px 0;
}
.two_top{
overflow: hidden;
}
</style>
<div class="one">
<div class="two_top">
<div class="two"></div>
</div>
<div class="three"></div>
</div>
在沒有添加two_top元素前,two和three是相鄰元素宋彼,都設(shè)置了margin弄砍,結(jié)果垂直外邊距重疊仙畦,并且two與父元素one的垂直外邊距也重疊。為解決重疊問題音婶,在two外面包裹一個two_top元素慨畸,設(shè)置overflow: hidden;使得two處于BFC區(qū)域,與外界元素隔離衣式,不相互影響寸士,垂直外邊距重疊問題消失。