各种清浮动方法总结
一:(1)clear清浮動
??
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.box1{float: left;width:200px;height: 200px;background-color: red;}.box2{float:left;clear:left;width:300px;height:300px;background-color: green;}</style> </head> <body><div class="box1"></div><div class="box2"></div> </body> </html>? ? (2)在浮動元素后添加空標簽,設置clear:both
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.box1{float: left;width:200px;height: 200px;background-color: red;}.box2{float:left;width:300px;height:300px;background-color: green;}.clear{clear: both;display: block;float: none;font-size:0;margin:0;padding:0;overflow: hidden;visibility:hidden;height:0;width:0;background: none;}</style> </head> <body><div class="box1"></div><div class="clear"></div><div class="box2"></div> </body> </html>二:overflow清浮動
? ??
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.box1{float: left;width:200px;height:200px;background: green;}.box2{float:left;width:200px;height:200px;background: navy;}.box3{height: 200px;width:400px;background: olive;}.main{overflow: hidden;}</style> </head> <body><div class="main"><div class="box1"></div><div class="box2"></div></div><div class="box3"></div> </body> </html>這里我們為box1,box2的父元素設置overflow:hidden,同樣可以達到清浮動的效果。
三:為父級元素定義高度
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.box1{float: left;width:200px;height:200px;background: green;}.box2{float:left;width:200px;height:200px;background: navy;}.box3{height: 200px;width:400px;background: olive;}.main{height:200px;}</style> </head> <body><div class="main"><div class="box1"></div><div class="box2"></div></div><div class="box3"></div> </body> </html>當我們使用浮動后,浮動元素的父級元素無法自動獲取高度,這時手動為其設置高度后可解決問題。
四:after偽類清浮動
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><style type="text/css">.box1{float: left;width:200px;height:200px;background: green;}.box2{float:left;width:200px;height:200px;background: navy;}.box3{height: 200px;width:400px;background: olive;}.clear:after{visibility:hidden;display:block;font-size:0;content:".";clear:both;height:0;}.clear{zoom:1;}</style> </head> <body><div class="main clear"><div class="box1"></div><div class="box2"></div></div><div class="box3"></div> </body> </html>說明:給容器添加clear類即可達到清除浮動的目的,因為清浮動需要在浮動元素后面,所以不用:before。首先用content屬性插入了一個句點,默認情況下content屬性插入的內容是行內元素,需要將其display:block,才能使clear:both生效,為了不讓插入的內容影響原來的布局,需要height:0將其高度設為0。
優化后的清除浮動的樣式:
.clear:after{content:".";display: block;height:0;clear:both;}.clear{zoom:1;}先總結到這。。。
轉載于:https://www.cnblogs.com/yingu/p/5322789.html
總結
- 上一篇: SetInterval和SettimeO
- 下一篇: Atitit.提升api兼容性的方法 v