CSS Validation DOCUMENTATION   |   CSS TUTORIAL   |   FORUM

CSS Hacks, Tricks, and Fixes

What are CSS Hacks?

A "CSS hack" is a way to work around a quirk in a rendering engine. It could also be a way to conceal flaws in your own CSS code. That is naughty. The former scenario is not a bad excuse to use CSS hacks.

When To Fight Mean

The rule is this:

"CSS hacks are acceptable in attempts to compensate for flaws or quirks in browsers or rendering engines."

They're not useful as complicated ways to fix simple CSS problems: don't do it. But they're great when you need to be sneaky to get something to look right in a particular browser. CSS hacks are usually browser-specific. Keep that in mind.

How CSS Hacks Work

CSS hacks use advanced, or technical, code that is only understood by suspecting browsers. This is convenient as it allows us to style the unsuspecting ones differently.

Dealing with Internet Explorer

You may find yourself needing to include entire style sheets, Javascript files or other content from a markup file in only certain versions of Internet Explorer, or even all of them.

IE does understand a certain tag syntax that other browsers will ignore.

For all versions of IE

<!--[if IE]>
 <link rel="stylesheet" type="text/css" href="ie-only.css" />
<![endif]-->

For a specific version of IE (replace "6" with the version you wish to target)

<!--[if IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6.css" />
<![endif]-->

For a group of versions of IE -- "lt" means "less than". "gt" means "greater than".

<!--[if gt IE 6]>
 <link rel="stylesheet" type="text/css" href="ie6-higher.css" />
<![endif]-->

Note that the above are not really "CSS hacks." They are possible ways to avoid needing true CSS hacks, described below.

Common CSS Hacks

  1. Clearfix is a popular fix that solves the following problem: suppose you have a <div> which contains two other <div> tags. Those two child tags are both floated for convience' sake. Suppose that there's even content between those two floated elements. If the content doesn't have at least the height of the floated elements, the container <div> will not span the height it should. Use this CSS: .clearfix:after {
       content: ".";
       display: block;
       clear: both;
       visibility: hidden;
       line-height: 0px;
       height: 0px;
    }
     
    .clearfix {
       display: inline-block;
    }
     
    html[xmlns] .clearfix {
       display: block;
    }
     
    * html .clearfix {
       height: 1%;
    }
    Then apply the "clearfix" class to the <div> container element. It should now stretch the height of the content inside it.