Monday, March 29, 2010

Importance of !important in CSS

CSS rules marked !important take precedence over later rules. Normally in CSS the rules work from top to bottom, so if you assigned a new style to an element further down the style sheet or in a secondary style sheet then the later rule would take precedence. !important ensures that this rule has precedence
Example #1: Normal behaviour
#example p {
color: blue;
}
...
#example p {
color: red;
}

The later rule overrides the earlier rule, and paragraphs within #example will be red.

Example #2: Using !important
#example p {
color: blue !important;
}
...
#example p {
color: red;
} 
The first rule now has precedence so the later rule is ignored and the paragraph will be blue.
Note:
Internet Explorer 6 will apply whatever the last style declared is, and takes no notice of !important declarations. So in Example #1 above, the other browsers would display the paragraph in blue but IE6 would display it in red.

No comments:

Post a Comment