CSS clearfix: make a floated element automatically fill it’s parent container

I’m not claiming for a second that clearfix is my invention.. If you want some history of it’s creators, check out this link:
http://www.positioniseverything.net/easyclearing.html

As with a lot of tips and techniques on this site, I’m just making a record of a technique that I use all the time and a version of it that I’m confident works. This also ensures that I have an online reference that isn’t going to disappear someday..

So anyway, onto clearfix 🙂

Basically this trick ‘fixes’ the problem that occurs when a floated element doesn’t automatically fill out it’s parent container..
Here’s some example HTML and an image to illustrate this scenario:

<div style="border:1px solid blue;padding:5px;">
	<div style="float:right;width:49%;height:50px;background:green;">
		&nbsp;
	</div>	
 
	<div style="width:49%;height:20px;background:red;">
		&nbsp;
	</div>
</div>


As you can see, the green div is extending out of it’s parent container.
i.e. it’s not expanding the container automatically.

To apply clearfix, simply use the following CSS:

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

And then add a class=”clearfix” to the parent container in your markup:

<div class="clearfix" style="border:1px solid blue;padding:5px;">
	<div style="float:right;width:49%;height:50px;background:green;">
		&nbsp;
	</div>	
 
	<div style="width:49%;height:20px;background:red;">
		&nbsp;
	</div>
</div>


Now you’ll see the green div expands the parent container automatically.

2 Responses to “CSS clearfix: make a floated element automatically fill it’s parent container”

  1. The best way to use a clearfix can be found at best clearfix ever. It doesn’t use class names to fix the problem but an automatic solution that should be applied to all block level elements except for the p and footer elements.

    • Hey Marc thanks for the comment. A slight tweak to your method would be to list your selectors with commas seperating them, then just have one block for the clearfix css rather than having to repeat it.
      i.e.
      /* our Global CSS file */
      article:after,
      aside:after,
      div:after,
      form:after,
      header:after,
      nav:after,
      section:after,
      ul:after
      { clear:both; content:”.”; display:block; height:0; visibility:hidden; }

      In regards to the actual CSS, I’ve gone with the version in this post after trying a bunch of variations that all broke somewhere along the line. This specific combination works for me in all situations in all browsers (that I care about).