The Advanced Clear-Fix

A common CSS issue is when a floated element is placed within a container div. What happens is that the floated element does not automatically force the height of the container to adjust, and the parent container then takes up zero space. When an element is floated, its parent no longer contains its children because the float is removed from the cascade. You can typically use two methods to fix this problem.

The most common, and simplest, fix is to use the following:

.clear {clear: both;}

In your HTML, you call this class as a separate, empty div after the floated elements:

<div class="clear"></div>

The problem with this approach is that it is not semantic HTML – since you’re calling an empty class – and it’s not descriptive. For screen readers, the class has no meaning, but will still be called. It also does not display the same across browsers.

A better method is to use the “clearfix” class. I’m not sure who originally developed it, but this slightly more robust snippet of CSS solves all of the above issues.

.clearfix:after {
content: ".";
visibility: hidden;
display: block;
clear: both;
_height: 0;
font-size: 0;
}

About the selectors and their properties:

height: 0; tells the div to not take up any space, and the underscore triggers “haslayout” in Internet Explorer, even fixing display errors in IE6.

content: “.”; Tells the HTML to append a period after the container div.

visibility: hidden; tells the page to hide the period.

display: block; forces the period to display as a block-level, rather than an inline element.

clear: both; clears the floated divs. This is the same as adding an unsemantic, empty “clear” div.

font-size: 0; is a precaution for Firefox since it sometimes adds a bit of space after the parent element. Setting the font-size to zero fixes this.

So there you have it – a completely valid, cross-browser supported, semantic way to fix parent-child relationships when you’re floating elements. Very handy in keeping footers at the bottom, where they should be!

Tags:

3 Responses to “The Advanced Clear-Fix”

  1. Your website is perfect, and I like this article. I find the information I need. I think I can find more useful information here, thanks.

  2. Paris Maloch says:

    This is a good piece of content, I was wondering if I could use this write-up on my website, I will link it back to your website though. If this is a problem please let me know and I will take it down right away.

  3. Vernon Mikez says:

    I am impressed by the way you mastered this topic. It is not often I come across a website with attractive articles like yours. I will bookmark your feed to keep up to date with your future updates.Like it and do keep up the complete work.

Leave a Reply