CSS清除浮动的简单方法

偶然发现的一个不错的文章,记录一下。

 

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值