Clearfix:强制元素自行清除其子元素

Avatar of Chris Coyier
Chris Coyier

如今这对你来说已经足够了(IE 8 及更高版本)

.group:after {
  content: "";
  display: table;
  clear: both;
}

将它应用于任何需要清除浮动元素的父元素。例如

<div class="group">
  <div class="is-floated"></div>
  <div class="is-floated"></div>
  <div class="is-floated"></div>
</div>

你会使用它来代替用类似 <br style="clear: both;" /> 在父元素底部清除浮动元素(容易忘记,不能直接在 CSS 中处理,非语义化),或在父元素上使用类似 overflow: hidden;(你并不总是希望隐藏溢出)。


现在谈谈历史!

这是最初流行的版本,旨在尽可能支持较旧的浏览器

.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}
.clearfix { display: inline-block; }
/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

然后,Jeff Starr 基于没有人使用 IE for Mac 的事实,提出了一个更简洁的版本,在这里记录,因为反斜杠技巧就是为了解决这个问题。

.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}
* html .clearfix             { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */

然后,使用“group”作为类名变得流行,这更简洁,也更语义化(来自 Dan Cederholm)。此外,content 属性甚至不需要空格,它可以为空字符串(来自 Nicolas Gallagher)。然后,在没有文本的情况下,font-size 就变得不必要了(来自 Chris Coyier)。

.group:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}
* html .group             { zoom: 1; } /* IE6 */
*:first-child+html .group { zoom: 1; } /* IE7 */

当然,如果你不再支持 IE 6 或 7,请删除相关的行。

更新于 2011 年 5 月 18 日:Nicolas Gallagher 再次提出了 “微型” clearfix。还可以查看这篇文章 额外的内容
.group:before,
.group:after {
  content: "";
  display: table;
} 
.group:after {
  clear: both;
}
.group {
  zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

查看此页面顶部,以获取 clearfix 的最新版本。

将来,我们可能能够使用

.group {
  display: flow-root;
}