<div> <!-- float container -->
<div style="float:left; width:30%;"><p>Some content</p></div>
<p>Text not inside the float</p>
<div style="clear:both;"></div>
</div>
First and foremost, this clearing method is not at all intuitive, requiring an extra element be added to the markup. One of the major premises of CSS is that it helps reduce the bloated HTML markup found it the average site these days. So having to re-bloat the markup just so floats can be kept within their containers is not an ideal arrangement.
Besides that, some browsers can have trouble with certain kinds of clearing elements in some situations. Mozilla is particularly sensitive to clearing problems.
Up 'til now there was no other way to do this, but no more! Thanks to the efforts of Tony Aslett, creator and operator of csscreator.com, we can now use advanced CSS to "clear" a float container in non-IE browsers and just let IE keep wrongly clearing itself. The upshot is that we now have the option to avoid adding that pesky clearing element to the HTML markup. Woohoo!
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
注意这个{display:block;}也被加入到:after中,因为默认情况下产生的那个元素的display属性值为inline,而display为inline的元素不能接受clear属性。
/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
/* End hide from IE-mac */
第一行是一条css注释,在注释的关闭标签(*/)前面正好有一个\符号,这就是精华所在,由于有这个反斜杠,IE/mac会忽略后面的关闭标签(*/),认为后面的仍然是注释(第2行被认为是注释),直到遇到一个*/为止,所以在IE/mac下上面的代码整个都被忽略了,而在 IE/win下不会,仅仅只把第 1 3行看作是注释,第2行看作是正常的css代码。
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
/* End hide from IE-mac */