[翻译]选一种更好的清除浮动方案

原文链接http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best

清除浮动的方式多种多样,以下每种方案在不同情况下,都有它出色的地方。

重提clearfix

CSS Mojo中Thierry Koblentz单独写了一篇文章来重温clearfix,强烈建议摈弃display: table的写法,而改用display: block的写法,其优点是避免包含块之间的margin塌陷(collapse)。

最近的一种代码量更少的清除浮动方案是这样的:

.container:after {
    content: '';
    display: block;
    clear: both;
}

“忘掉上面的写法吧”,让我们看看在现代浏览器上怎么写

CSS Mojo中Thierry Koblentz还指出,针对现代浏览器开发时,我们可以弃用zoom:before等属性/值,简化写法:

.container:after {
    content: '';
    display: table;
    clear: both;
}

这种写法特意没有支持IE6/7……

提醒一句:如果你重新开始一个新项目,放心做吧,但是不要使用这种写法,虽然你没有支持旧版本的IE浏览器,但是可以避免margin塌陷。

代码更少的清除浮动

这是最近广为接受的一种方案Micro Clearfix by Nicolas Gallagher

.container:before,
.container:after {
  content:"";
  display:table;
}
.container:after {
  clear:both;
}
.container {
  zoom:1; /* For IE 6/7 (触发 hasLayout) */
}

overflow属性

当定位元素不显示在容器外时,这种方案通常是首选。

http://www.quirksmode.org/css/clearing.html,这篇文章解释了这种写法的一个常见问题,也就是在容器上设置width: 100%

.container {
    overflow: hidden;
    display: inline-block; /* 用来触发IE的hasLayout */
    display: block; /* 覆盖上一条属性,重新设置为block */
}

触发IE浏览器的hasLayout不止有display这一个属性,其他的属性也可以做相同的工作。

.container {
    overflow: hidden; /* 清除浮动 */
    zoom: 1;  /* 用来触发IE的hasLayout */
    display: block; /* 元素必须为块级元素,如果只应用于块级元素,这条可不写 */
}

overflow清除浮动的另一种方案是使用下划线hack,IE浏览器会识别带有下划线的属性,但是其他的浏览器不可以,下面是利用zoom属性触发IE hasLayout的写法:

.container {
    overflow: hidden;
    _overflow: visible; /* for IE */
    _zoom: 1; /* for IE */
}

尽管这样很有用,但理想方案是不使用hack。

:after 伪元素

这种旧的方案以使用杂乱的CSS为代价,但好处是它会允许定位元素超出容器的边界。

http://www.positioniseverything.net/easyclearing.html

.container {
    display: inline-block;
}
.container:after {
    content: " ";
    display: block;
    height: 0;
    clear: both;
    overflow: hidden;
    visibility: hidden;
}
.container {
    display: block;
}

使用行内样式,clear属性

一种快捷但是很乱的写法

<br style="clear:both" /> <!-- So dirty! -->

因为很多因素,这种方案很不理想:

不符合代码复用的思想,让你的代码看起来很不专业。
以后有其他的清除浮动方案可使用时,你必须回头来整理这些杂乱的html。

posted @ 2016-03-15 18:49  钟山  阅读(171)  评论(0编辑  收藏  举报