tags:

views:

40

answers:

2

I am using the !important tag in CSS to take precedence over later rules.

However, I realized that if another programmer defined in a later rule !important, the style assigned will be the latest !important one.

For example: my css - loaded first.

#div{
    color: green !important;
}

the programmer's css:

#div {
    color: red !important;
}

it will be red, although I would like it to be green.

Is the suitable way to fix it is to download my css before the end of </body> tag? What if the page couldn't not be loaded quickly? is it right to download it at the beginning and at the end of the document?

+1  A: 

The appropriate thing is almost never to use !important, partly for the reason you mention. !important means, my rule comes first, except when other rules also have !important, at which point the strange and exotic world of CSS specificity kicks in. Just make sure your rule is more specific than theirs.

To find out more about specificity, read Chris Coyier's excellent introduction.

Dominic Rodger
And don't forget Andy Clarke's wonderful CSS: Specificity Wars http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
Yi Jiang
@Yi Jiang - that's awesome - thanks!
Dominic Rodger
+1  A: 

You can increase the rule specificity.

Example: The rule with selector "#div" is less specific than "#div .test". If two rules have !important, the more specific wins.


But, of couse, the programmer can make a more specific rule yet.

Ex: You change to #myBody #div, and he change to html #myBody #div. So, you CAN'T stop programmer from overwrite your rules.

See here.

Topera