標籤:style http os io strong ar for div 代碼
原文連結:http://www.45eggs.com/xhtml-css/2011/css-clearfix.html
一,什麼是.clearfix
你只要到Google或者Baidu隨便一搜"css清除浮動",就會發現很多網站都講到"盒子清除內部浮動時可以用到.clearfix"。
.clearfix:after { content: " "; display: block; clear: both; height: 0;}.clearfix { zoom: 1;}<div class="clearfix"> <div class="floated"></div></div>
上面的代碼就是.clearfix的定義和應用,簡單的說下.clearfix的原理:
1、在IE6, 7下zoom: 1會觸發hasLayout,從而使元素閉合內部的浮動。
2、在標準瀏覽器下,.clearfix:after這個偽類會在應用到.clearfix的元素後面插入一個clear: both的區塊層級元素,從而達到清除浮動的作用。
<div> <div class="floated"></div></div><div style="clear: both"></div>
二,.clearfix的弊端
在上面的代碼中可以看到,拋開IE6, 7不談,.clearfix在標準瀏覽器下插入了一個clear: both的元素,這樣很可能清除掉不必要的浮動。舉例來說明:
<!DOCTYPE html><html><head> <title>Demo</title> <style type="text/css"> html, body { padding: 0; margin: 0; } ul { margin: 0; padding: 0; } .clearfix:after { content: " "; display: block; clear: both; height: 0; } .clearfix { zoom: 1; } .left-col { background: red; float: left; width: 100px; height: 300px; } .right-col { margin-left: 100px; } .menu { border: 1px solid #000; } .menu li { float: left; display: block; padding: 0 1em; margin: 0 1em 0 0; background: #ccc; } .placeholder { background: yellow; height: 400px; } </style></head><body> <div class="left-col"> </div> <div class="right-col"> <ul class="menu"> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> </ul> <div