HTML and CSS | Clearfix for Older IE Versions


 

Clearfix for Older IE Versions

Older versions of IE don't support generated content CSS selectors, which means that our "clearfix" solution won't work. So we have to tell IE to focus on the element the fix has been applied to.

IE has a special feature called hasLayout. It's sort of a voodoo declaration baked into the browser. Sometimes an element has hasLayout and sometimes it doesn't, giving it special CSS powers. No other browser has this, so we are exploiting a "feature" in IE to get it to work around a failure to honor the CSS specification... but I digress. By figuring out how to trigger hasLayout onto the element through CSS, we can get around the generated content problem.

The zoom CSS property is such a property! So the new, finalized workaround looks like this:

<style type="text/css">
.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden; 
}
</style>
<!--[if IE]>
<style type="text/css">
.clearfix {
    zoom: 1;     /* triggers hasLayout */     
    }  /* Only IE can see inside the conditional comment
    and read this CSS rule. Don't ever use a normal HTML
    comment inside the conditional comment or it will
    close prematurely. */
</style>
<![endif]-->

The zoom property is an IE-only CSS property that's not supported in older browsers. (The property helps set the size of elements, if you want to know.) Notice that we included a conditional comment here so that only IE browsers to see and render this code.

So, yes, we are using an IE-only CSS property to trigger an IE-only hasLayout effect through IE-only comments to make the IE browser work for us. CSS developers sure are a sneaky lot!