BFC
BFC (Block formatting context) “塊級格式化上下文”
它是頁面中的一塊渲染區域,有一套渲染規則,決定了其子元素如何佈局,以及和其他元素之間的關係和作用。
- 觸發
滿足下列條件之一就可觸發BFC
【1】根元素,即HTML元素
【2】float的值不爲none
【3】overflow的值不爲visible
【4】display的值爲inline-block、table-cell、table-caption
【5】position的值爲absolute或fixed
- 特性
【1】阻止垂直外邊距(margin-top、margin-bottom)摺疊
屬於同一個BFC的兩個相鄰塊級子元素(元素都要在文檔流中)的上下margin會發生重疊—— 分爲兩個BFC就可以消除這種margin 重疊
<style>
.dv {
width: 400px;
height: 400px;
border: 1px solid slateblue;
}
.dv2 {
width: 200px;
height: 100px;
background: salmon;
margin-bottom: 30px;
}
.dv3 {
width: 200px;
height: 100px;
margin-top: 60px;
background: seagreen;
}
<div class="dv">
<div class="dv2">
</div>
<div class="dv3">
IE6、IE7中, // function foo(){ // console.log(a); // } // function bar(){ // var a =3 ;
</div>
</div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
解決
觸發其中一個div的BFC,使得兩個div不在同一個 BFC內,這樣就可以阻止這兩個div的margin重疊
.dv4{
/* overflow: hidden; */
/* display: inline-block; */
position: absolute;
}
- 1
- 2
- 3
- 4
- 5
【2】包含浮動元素
可以包含它內部的所有元素,包括浮動元素——因此一清除內部浮動
<style>
.second{
width: 400px;
padding: 10px;
border: 1px solid slateblue;
}
.float{
float: left;
width: 200px;
height: 50px;
background: salmon;
}
.s1{
background: slategray;
}
</style>
<div class="second">
<div class="float">
</div>
<div class="s1">
IE6、IE7中, // function foo(){ // console.log(a); // } // function bar(){ // var a =3 ;
IE6、IE7中, // function foo(){ // console.log(a); // } // function bar(){ // var a =3 ;
</div>
</div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
元素內容比較多的時候,內容會環繞着浮動的元素
清除環繞
,爲其本身創建一個BFC
.s1{
overflow: hidden;
background: slategray;
}
- 1
- 2
- 3
- 4
元素內容比較少的時候,會出現高度坍塌, 足夠的文本去一個浮動的元素 , 浮動元素脫離文檔流,父元素(class=second)高度就會隨着文本的減少而降低 ,父元素未被浮動元素撐開,父元素的高度坍塌。
改變坍塌
:爲父元素創建一個BFC
.second{
width: 400px;
padding: 10px;
border: 1px solid slateblue;
overflow: hidden;
//或者 overflow: auto;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
整理自:
https://blog.csdn.net/liuliuliu_666/article/details/70847566
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
</div>