1.什麼是BFC?css
BFC是Block farmatting context 的簡寫。翻譯過來即:塊級格式化上下文。farmatting context 簡單理解就是一種渲染規則, 規定了頁面 上元素如何渲染,元素與元素之間的關係。具體就BFC來講,此規則或者說此渲染區域具備塊與塊之間 相互獨立,內部元素互不影響的特色。 BFC的佈局規則:
內部元素會在垂直方向按順序排列。html
接上條規則,垂直順序排列的元素的距離取決於margin的大小。相鄰的兩個元素的margin會重疊。面試
每一個元素的左邊會盡量的去接觸盒子(造成BFC的元素)的左邊。佈局
BFC的元素不會和float的元素重疊。spa
BFC的元素內外互不影響。翻譯
BFC高度包含浮動元素高度。3d
2.如何生成BFCcode
常見的:
float屬性爲非none時,如left,right。htm
position屬性爲fixed或者absolute時。blog
display屬性爲inline-block或者爲table-cell時。
overflow爲非visible時。
3.BFC有什麼用?
1.能夠清除浮動:
//清除浮動前的代碼: //css: .box{ border:1px solid red; width: 400px; } .inner-box{ float: left; width: 200px; height: 100px; background: #ccc; } //html <div class="box"> <div class="inner-box"></div> <div class="inner-box"></div> </div>
能夠看到邊框爲紅色的div由於浮動塌陷了,咱們給此div加上overflow:hidden,造成BFC:
//css .box{ border:1px solid red; width: 400px; overflow: hidden; } .inner-box{ float: left; width: 200px; height: 100px; background: #ccc; } //html: <div class="box"> <div class="inner-box"></div> <div class="inner-box"></div> </div>
能夠看到div被撐起來了。用的如下規則:
BFC高度包含浮動元素高度。
2.左邊固定,右邊自適應佈局:
//css .box{ border:1px solid red; width: 400px; height: 300px; position: relative; } .a{ float: left; width: 200px; height: 100px; background: olivedrab; } .b{ background: #777; height: 300px; } //html: <div class="box"> <div class="a">我是a</div> <div class="b">我是b</div> </div>
(能夠用這個作作文字環繞圖片什麼的。。) 再看加上float,造成BFC:
//css .box{ border:1px solid red; width: 400px; height: 300px; } .a{ float: left; width: 200px; height: 100px; background: olivedrab; } .b{ background: #777; height: 300px; overflow: hidden; } //html <div class="box"> <div class="a">我是a</div> <div class="b">我是b</div> </div>
左邊就自適應寬度了。規則:
overflow爲非visible時。
3.解決margin重疊問題:
//css .box{ border:1px solid red; width: 400px; height: 300px; } .a{ width: 400px; height: 100px; background: olivedrab; margin-bottom: 100px; } .b{ background: #777; height: 100px; overflow: hidden; margin-top: 100px; } //html <div class="box"> <div class="a">我是a</div> <div class="b">我是b</div> </div>
看代碼能夠知道a的margin-bottom加b的margin-top 等於 100+100,然而空白區域只有100像素。這就是發生了margin重疊! 那咱們如何來解決這個問題呢?咱們知道有這個規則:
接上條規則,垂直順序排列的元素的距離取決於margin的大小。相鄰的兩個元素的margin會重疊。
那咱們反其道而行之不就好了嗎! 因而咱們改造結構,讓a和b不在同一個BFC內:
//css .box{ border:1px solid red; width: 400px; } .a{ width: 400px; height: 100px; background: olivedrab; margin-bottom: 100px; } .b{ background: #777; height: 100px; overflow: hidden; margin-top: 100px; } .b-box{ overflow: hidden; } //html <div class="box"> <div class="a">我是a</div> <div class="b-box"> <div class="b">我是b</div> </div> </div>
能夠看到,距離爲200PX了。
---------------------------------------結束分割線--------------------------------------------------------------------
之前老是聽別人說BFC,專門瞭解了一下寫了此文章。忘了拿出來看看。說不定面試也會問到一些呢。- - 暫時就寫到這裏了。有什麼問題請多多吐槽。