How to Avoid CSS Hacks for Internet Explorer

With most web developers still confusing about the usage of CSS hacks and Internet Explorer some information about the code testing and implementing good CSS hacks is still necessary. The following examples from the code help you to find out how to clean up some CSS hacks for IE.CSS Hacks to remember

According to Tantek Çelik, the CSS hacks guru, there are several rules that explain how CSS hacks should be designed for such a troublesome browser as Internet Explorer. First of all, they should be valid. The second rule is that CSS hacks should target only old/abandoned/frozen browsers/user-agents. And the last thing to know is that they should be ugly. Tantek also explains that using a feature of CSS is not a hack.

The star html bug and the underscore hack are the most often IE-specific hacks in the code. Let’s find out how they can be replaced with the same CSS feature-based solution. Here are some code samples of them both.

The Star HTML Bug

Targeting current as well as future UAs, this hack violates Tantek’s second rule. It can be found as a stand alone rule as well as an override to some other rule in a style sheet:

* html div#header {margin-top:-3px;}

.promo h3 {min-height:21px;}
* html .promo h3 {height:21px;}

The Underscore Hack

This hack violates Tantek’s first two rules: first of all, it is invalid according to the W3C CSS Validator. It also targets current UAs:

ol {padding:0; _padding-left:5px;}

Child Selectors to Fix the Problem

CSS Hacks for all

With the child selector we can replace both the underscore hack as well as the star html bug. The first step is to write the rules with selectors that can be applied to all browsers:

div#header {}

.promo h3 {}

ol {padding:0;}

Then, add the IE-specific declarations to these rules:

div#header {margin-top:-3px;}

.promo h3 {height:21px;}

ol {padding:0 0 0 5px;}

Add the second rule after each rule. The selector of the second rule must use a child selector. Now correct any IE-specific declarations in this new rule:

div#header {margin-top:-3px;}
body > div#header {margin-top:0;}

.promo h3 {height:21px;}
.promo > h3 {height:auto; min-height:21px;}

ol {padding:0 0 0 5px;}
html > body ol {padding:0;}

Thus, you have no more hacks. Operating in strict mode and trying to bar some complicated stuff in your code, your CSS will work perfectly across all browsers.

Comments are closed.