CSS清除浮動的簡單方法

來源:互聯網
上載者:User

偶然發現的一個不錯的文章,記錄一下。

 

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.

 

 

附上demo

 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.