之前在寫html和css的時候,兩個div都設置了margin不一樣的上下值。寫完後我開心的打開頁面,爲毛兩個應該隔的比較開的div,距離並非我設置的margin值。因而我從marigin重合搜索到了BFC,因而我blahblah地看了一通,卻沒有看的很懂,只知其一;不知其二的我煩躁的放棄了。
最近忽然想深刻的瞭解下css,在看了幾篇文章後,裏面涉及到了我之前的問題,並從css標準和原理上講解了,配合上例子,有了種豁然開朗的感受:原來margin會摺疊是這個緣由!因此想把這種感受記錄下來,也是一份對這部分知道的總結和鞏固。css
塊級格式化上下文(block formatting context) 是頁面 CSS 視覺渲染(visual CSS rendering)這個過程當中的一個概念。它是決定塊盒子的佈局及浮動元素相互影響的一個因素。html
根元素ide
絕對定位元素 (position 爲 absolute 或 fixed)佈局
float的值不爲noneflex
display的值爲:inline-block, table-cell, table-captions, flexspa
overflow的值不爲visiblecode
屬於同一個BFC的兩個相鄰Box的margin會發生折orm
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <style> div { width: 100px; height: 100px; } .a { background: lightblue; margin-bottom: 20px; } .b { background: orange; margin-top: 20px; } </style> </head> <body> <div class="a"></div> <div class="b"></div> </body> </html>
那如何阻止margin摺疊呢,只要將其中一個box建立新的BFC就好了。(能夠嘗試不一樣建立BFC的方法嘗試,代碼註釋了)htm
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <style> * { margin: 0; } body { background: pink; } .p { width: 150px; height: 150px; margin-top: 20px; background: lightblue; } .s { width: 100px; height: 100px; margin-top: 30px; background: orange; } .bfc { overflow: hidden; /* display: inline-block; */ /* position: absolute; */ /* float: left; */ } </style> </head> <body> <div class="p"> <div class="s"></div> </div> <div class="p bfc"> <div class="s"></div> </div> </body> </html>
在計算BFC元素高度時,浮動元素的高度也會計算進去,因此能夠達到清除浮動的效果(能夠將下例嘗試不一樣建立BFC的方法來清除浮動)blog
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <style> * { margin: 0; } .wrap { width: 80px; border: 5px solid orange; } .a { width: 80px; height: 80px; background: lightblue; } .fl { float: left; } .bfc { overflow: hidden; /* display: inline-block; */ /* position: absolute; */ /* float: left; */ } </style> </head> <body> <div class="wrap"> <div class="a fl"></div> </div> <div style="clear: both;"> <br> <div class="wrap bfc"> <div class="a fl"></div> </div> </body> </html>
第一次寫這類總結,若是有什麼不對的,但願你們和諧交流。
BFC還有一些其餘的佈局規則,我只寫出了我之前疑惑的點,也感謝我參考的幾篇文章,下面是連接,你們有興趣能夠深刻研究下。