清除浮動的四種方法
阿新 • • 發佈:2020-08-26
首先,如果父盒子我們寫頁面的時候沒有給固定高度,它的高度就是子盒子內容的高度。
但是我們如果將子盒子浮動後,那麼父盒子就沒有高度了。所以,我們清除浮動,是清除浮動帶來的影響。並不是清除浮動。
作為一個有節操的程式設計師,我們平時使用的是第四種更多!
方案四:使用before和after雙偽元素清除浮動,給父元素加一個類.clearfix
.clearfix:after, .clearfix:before { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; }
本文一共介紹了4種方式清除浮動。效果如下:
程式碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> .demo { width: 100px; border: 1px solid #000; } .pink { width: 50px; height: 50px; background-color: pink; float: left; } .skyblue { width: 60px; height: 60px; background-color: skyblue; float: left; } /* 解決方案一 額外標籤法*/ .demo1 { width: 100px; border: 1px solid #000; } .pink1 { width: 50px; height: 50px; background-color: pink; float: left; } .skyblue1 { width: 60px; height: 60px; background-color: skyblue; float: left; } .clear { clear: both; } /* 解決方案二 父元素新增overflow:hidden*/ .demo2 { width: 100px; border: 1px solid #000; overflow: hidden; } .pink2 { width: 50px; height: 50px; background-color: pink; float: left; } .skyblue2 { width: 60px; height: 60px; background-color: skyblue; float: left; } /* 解決方案三 使用after偽元素清除浮動*/ .demo3 { width: 100px; border: 1px solid #000; } .clearfix:after { /*偽元素是行內元素 正常瀏覽器清除浮動方法*/ content: ""; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { *zoom: 1; /*ie6清除浮動的方式 *號只有IE6-IE7執行,其他瀏覽器不執行*/ } .pink3 { width: 50px; height: 50px; background-color: pink; float: left; } .skyblue3 { width: 60px; height: 60px; background-color: skyblue; float: left; } /* 解決方案四 使用before和after雙偽元素清除浮動*/ .demo4 { width: 100px; border: 1px solid #000; } .clearfix:after, .clearfix:before { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } .pink4 { width: 50px; height: 50px; background-color: pink; float: left; } .skyblue4 { width: 60px; height: 60px; background-color: skyblue; float: left; } </style> <body> <p> 首先,如果父盒子我們寫頁面的時候沒有給固定高度,它的高度就是子盒子內容的高度。</p> <p> 但是我們如果將子盒子浮動後,那麼父盒子就沒有高度了。所以,我們清除浮動,是清除浮動帶來的影響。並不是清除浮動。 </p> <div class="demo"> <div class="pink"></div> <div class="skyblue"></div> </div> <br><br><br> <p>方案一:額外標籤法</p> <div class="demo1"> <div class="pink1"></div> <div class="skyblue1"></div> <div class="clear"></div> </div> <p>方案二:父元素新增overflow:hidden</p> <div class="demo2"> <div class="pink2"></div> <div class="skyblue2"></div> </div> <p>方案三:使用after偽元素清除浮動</p> <div class="demo3 clearfix"> <div class="pink3"></div> <div class="skyblue3"></div> </div> <p>方案四:使用before和after雙偽元素清除浮動</p> <div class="demo4 clearfix"> <div class="pink4"></div> <div class="skyblue4"></div> </div> </body> </html>