Using !important with CSS

by Rekha 2009-11-20 16:32:56

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.

The easiest way to explain this is with some examples.
Example #1: Normal behaviour

Let's say we declared paragraph tags in the #example div to be colored blue, and then further down the style sheet (or in another style sheet also linked to in the page) that they be colored red:

#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

If we assigned !important to the first rule, then the second rule would be ignored because the first rule now has precedence:

#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.
Example #3: !important declared again

If the !imporant declaration is used again in the later definition, then the normal cascading rules will apply, and the style assigned will be the latest !important one:

#example p {
color: blue !important;
}
...
#example p {
color: red !important;
}

In the above example the paragraph will be red.
Example #4: Inline styles

Ideally you shouldn't use inline styles, but here's a couple of examples when using them with !important.

!important in the CSS style sheet will override any inline styles as well:

CSS: #example p {
color: blue !important;
}

HTML:

This paragraph has an inline style




In the above example, the paragraph will be in blue text and not green as in the inline style because of the !important declaration in the CSS.
Example #5: Inline styles with !important

However, if you add !important to the inline style then that will of course have precedence:

CSS: #example p {
color: blue !important;
}

HTML:

This paragraph has an inline style




So in the above example the paragraph will be green.

Tagged in:

1526
like
0
dislike
0
mail
flag

You must LOGIN to add comments