BFC:塊級格式化上下文
BFC是一個獨立的佈局環境,其中的元素佈局是不受外界的影響,而且在一個BFC中,塊盒與行盒(行盒由一行中全部的內聯元素所組成)都會垂直的沿着其父元素的邊框排列。
一、float的值不是none
。
二、position的值不是static
或者relative
。
三、display的值是inline-block
、table-cell
、flex
、table-caption
或者inline-flex
四、overflow的值不是visible
html
1.利用BFC避免margin重疊。
2.自適應兩欄佈局
3.清除浮動。佈局
清除浮動主要是爲了解決,父元素由於子級元素浮動引發的內部高度爲0的問題。
在最後一個浮動標籤後,新加一個標籤,給其設置clear:both;(不推薦)
優勢:通俗易懂,方便
缺點:添加無心義標籤,語義化差flex
<style> .div1 { background: #00a2d4; } .left { float: left; width: 200px; height: 200px; background: #9889c1; } .right { float: right; width: 200px; height: 200px; background: orangered; } .clear { clear: both; } </style> </head> <body> <div class="div1"> <div class="left">Left</div> <div class="right">Right</div> <div class="clear"></div> </div> <div class="div2"></div> </body>
經過觸發BFC方式,實現清除浮動。(不推薦)
優勢:代碼簡潔
缺點:內容增多的時候容易形成不會自動換行致使內容被隱藏掉,沒法顯示要溢出的元素code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .div1 { background: #00a2d4; overflow: hidden; } .left { float: left; width: 200px; height: 200px; background: #9889c1; } .right { float: right; width: 200px; height: 200px; background: orangered; } </style> </head> <body> <div class="div1"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"></div> </body> </html>
優勢:符合閉合浮動思想,結構語義化正確。
缺點:ie6-7不支持僞元素:after,使用zoom:1觸發hasLayout。htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .div1 { background: #00a2d4; } .left { float: left; width: 200px; height: 200px; background: #9889c1; } .right { float: right; width: 200px; height: 200px; background: orangered; } .clearfix:after { content: ""; /*內容爲空*/ display: block; /*轉換爲塊級元素*/ height: 0; /*高度爲0*/ clear: both; /*清除浮動*/ visibility: hidden; /*隱藏盒子*/ } .clearfix { *zoom: 1; /*IE6\7的處理方式*/ } </style> </head> <body> <div class="div1 clearfix"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"></div> </body> </html>
優勢:不只能夠清除浮動,也能夠解決高度塌陷的問題(給父盒子添加類名clearfix)
缺點:用zoom:1觸發hasLayout.it
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .div1 { background: #00a2d4; } .left { float: left; width: 200px; height: 200px; background: #9889c1; } .right { float: right; width: 200px; height: 200px; background: orangered; } .clearfix:after, .clearfix:before { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } </style> </head> <body> <div class="div1 clearfix"> <div class="left">Left</div> <div class="right">Right</div> </div> <div class="div2"></div> </body> </html>