The clearfix hack is a popular way to contain floats without resorting to using presentational markup. This article presents an update to the clearfix method that further reduces the amount of CSS required.

Update [25 April 2011]: The micro clearfix code has been updated following further testing.

Demo: Micro clearfix hack

Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+

The “micro clearfix” method is suitable for modern browsers and builds uponThierry Koblentz’s “clearfix reloaded”, which introduced the use of both the:before and :after pseudo-elements.

Including the :before selector is not necessary to clear the floats, but itprevents top-margins from collapsing in modern browsers. This ensures that there is visual consistency with IE 6/7 when zoom:1 is applied.

However, there are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.

Here is the updated code (I’ve used a shorter class name too):

/* For modern browsers */.cf:before,.cf:after {    content:"";    display:table;}.cf:after {    clear:both;}/* For IE 6/7 (trigger hasLayout) */.cf {    zoom:1;}

The main difference from previous clearfix methods is that “micro clearfix” generates pseudo-elements without inserting any content and usesdisplay:table rather than display:block. Because the pseudo-elements are empty, there is no potential for unwanted space to appear before or after the content of the element. This avoids the need to use the height:0 workaround.

Versions of Firefox prior to Firefox 3.5 will benefit from using Thierry’s method with the addition of visibility:hidden to hide the inserted character. This is because legacy versions of Firefox need content:"." to avoid extra space appearing between the body and its first child element (e.g.http://jsfiddle.net/TjW6c/43/).

Alternative float-containment methods that create a new block formatting context, such as applying overflow:hidden or display:inline-block to the container element, will also avoid this behaviour in legacy versions of Firefox.






Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >



如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。