You are hereBlogs / alif's blog / Useful Simple CSS Cross Browser Tricks: !important

Useful Simple CSS Cross Browser Tricks: !important


By alif - Posted on 02 January 2009

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:

  1. .footerText {
  2. font-size: 12px;
  3. }

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

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

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:

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

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:

  1. .testDiv {
  2. width: 100px;
  3. padding: 5px 10px;
  4. }

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.

  1. .testDiv {
  2. padding: 5px 10px;
  3. width: 100px !important;
  4. width: 120px;
  5. }

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

Tags