H Bellamy H Bellamy - 4 months ago 11
CSS Question

What is a clearfix?

Recently I was looking through some website's code, and saw that every

had a class

After a quick Google search, I learned that it is for IE6 sometimes, but what actually is a clearfix?

Could you provide some examples of a layout with a clearfix, compared to a layout without a clearfix?


If you don't need to support IE9 or lower, you can use flexbox freely, and don't need to use floated layouts.

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, Safari 6.1 (including Mobile Safari) and Android's default browser 4.4.

For a detailed browser list see: http://caniuse.com/flexbox.

(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 its child elements, 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 class="clearfix">
    <div style="float: left;" class="clearfix">Sidebar</div>
    <!-- No Clearing div! -->

Read about it in this article - by Chris Coyer @ CSS-Tricks