你知道有关清除浮动闭合的最佳方案吗?-CSS .clearfix-是什么-如何使用

一,什么是.clearfix

很多网站都讲到一个盒子清除内部浮动时可以用到.clearfix。

1
2
3
4
5
6
7
8
9
.clearfix:after {
  content: " ";
  display: block;
  clear: both;
  height: 0;
}
.clearfix {
  zoom: 1;
}
1
2
3
<div class="clearfix">
  <div class="floated"></div>
</div>

上面的代码就是.clearfix的定义和应用,简单的说下.clearfix的原理:

  • 在IE6, 7下zoom: 1会触发hasLayout,从而使元素闭合内部的浮动。
  • 在标准浏览器下,.clearfix:after这个伪类会在应用到.clearfix的元素内部插入一个clear: both的块级元素,从而达到清除浮动的作用。这时的代码相当于:
    1
    2
    3
    4
    <div>
      <div class="floated"></div>
      <div style="clear: both"></div>
    </div>

二,总结

在IE6, 7下面只要是触发了hasLayout的元素就可以清除内部浮动了。而在标准浏览器下面清除元素内部浮动的方法有很多,大多数的情况下.clearfix:after都可以满足需求。除了.clearfix:after这种方式,其余的方法无非就是产生新的Block Formatting Context以达到目的……

It’s worth noting that today, the use of floated elements for layout is getting more and more discouraged with the use of better alternatives.

  • display: inline-block – Better
  • Flexbox – Best (but limited browser support)

Flexbox is supported from Firefox 18, Chrome 21, Opera 12.10, and Internet Explorer 10, but no support for Safari (including Mobile Safari) or Android’s old default browser.

(Perhaps once it’s position is established completely, it may be the absolutely recommended way of laying out elements.)


A clearfix is a way for an element to automatically clear after itself, so that you don’t need to add additional markup. It’s generally used in float layouts where elements are floated to be stacked horizontally.

The clearfix is a way to combat the zero-height container problem for floated elements

A clearfix is performed as follows:

.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don’t require IE<8 support, the following is fine too:

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

Normally you would need to do something as follows:

<div style="float: left;">Sidebar</div>
<div style="clear: both;"></div> <!-- Clear the float -->

With clearfix, you only need to

<div style="float: left;" class="clearfix">Sidebar</div>
<!-- No Clearing div! -->
Top Down