Fighting collapsing DIVs with CSS clearfix

Fighting collapsing DIVs with CSS clearfix

Last updated:

One of the most annoying CSS features that really baffles many a CSS learner is how <div>s seem to collapse when they only had one element and you use something like float:left; or float:right; on the lone child.

Fret not mein Freund for your prayers have been answered.

Add this to your stylesheets:

.clearfix:before,
.clearfix:after {
   display: table;
   content: "";
   line-height: 0;
}
.clearfix:after {
    clear: both;
}

Then you add clearfix as a class for every div you don't want to collapse, like this.

<div class="clearfix">
    <div style="float:left;">
        //some content.. 
    </div>
</div>

This is but one version of clearfix. The one I usually use and has worked so far.

  • There are other versions too, like this article from webtoolkit on clearfix
  • (Another solution using overflow:auto)[http://queirozf.com/entries/stop-a-div-from-collapsing-when-you-float-elements-inside-it)