Weblog of Abdullah Rubiyath :: Alif

Exploring the Web: An apple a day

Useful Simple CSS Cross Browser Tricks: !important

Tweet
Fri, 01/02/2009 - 22:11 -- alif

The CSS !important keyword is a useful keyword for Old browsers (IE-6, IE 5.5) as well as new browsers.

For new browsers, it can be used to override all other values, for example:

If I have a CSS declared:


.footerText {
font-size: 12px;
}

Now, if on another CSS or even in the same file the following is declared anywhere (before or after the previous declaration):


.footerText {
font-size: 14px !important;
}

This CSS declaration will override the first one.

When resolving issues for IE-6, this keyword is also very useful. The following are two such examples:

#1: Resolving PNG (using GIF on IE-6): IE-6 doesnot support PNG files, and I Know there are plenty of Javascript 'hacks' which can be applied to fix the PNG issue, I however, prefer to use CSS (which is also very simple).

Consider the following case: I have a PNG file, stored in /images/blog_img.png which I want to display for IE-7, FF and Safari users, however I also want to show IE-6 users an alternative 'degraded' quality image. So, I do the following:


.blogDiv {
background: url(/images/blog_img.png) top left no-repeat !important;
background: url(/images/ie6/blog_img.gif) top left no-repeat;
}

With the above code, browsers like IE-7, FF, Safari will use the first declaration (i.e !important) and that will over-ride any other declaration applied later. So, PNG file will be used to declare as background.

However, on IE-6 the keyword !important is not taken into consideration, so, the 2nd declaration (since its declared after 1st one) will take effect, and hence, the background displayed will be a GIF File.

#2: Padding issues on IE-6: Though some people might say this is a trivial issue, but I still consider it an issue. When you declare padding on CSS, browsers other than IE-6 & IE-5.5, actually adds the padding pixels to the specified element. For example:


.testDiv {
width: 100px;
padding: 5px 10px;
}

With the above declaration, the testDiv will have a width of 100px + 20px = 120px, So, the contents will be contained within 100px. But, IE-6/5.5, will apply the padding on the 100px, so, the final width of the element (that will contain the Content) will be 80px (80px + 20px).

Again, using !important keyword resolves this issue.

.testDiv {
padding: 5px 10px;
width: 100px !important;
width: 120px;
}

IE-6/5.5 will simply pick the 2nd declaration of width and ignore the first one.