Home  »  Code Snippets   »   css !important

When to use !important in css?

!important property value was introduced in the early 90s to help override styles easily. Since then, it is working as the same as it was 20 years ago. It has only one job. Just override everything that has the higher precedence.

Just like normal cascading CSS, !important also follows the cascading behavior. That is inline CSS with !important will take over all others.

Here is what the inline rule looks like:

<p style="color:red">The dead speak! The galaxy has heard a mysterious broadcast, a threat of REVENGE in the sinister voice of the late EMPEROR PALPATINE.
</p>

This will override the browser style which is the black color most of the time.

Edit Example

Why do we use !important though? 

The browser will render the font red even without !important property.

But here is what happens when we add any CSS properties to the document.

p{color:blue !important}

the code will change the color red to blue because of !important.

Edit Example

As we know the inline CSS will have the highest precedence, !important will still manage to override the style.

This is helpful most of the time but can lead to confusion sometimes because when used externally, It will follow the cascading order anyways.

Here is the same example with multiple rules.

body p{color:brown !important}

p{color:blue !important}

Edit Example

In the above example, the text renders brown. despite of being above the second rule, the second rule can't override the first one because they both uses !important but the first rule is having higher precedence.

Check out what happens if we add !important to the inline element itself:

<p style="color:red !important;">The dead speak! The galaxy has heard a mysterious broadcast, a threat of REVENGE in the sinister voice of the late EMPEROR PALPATINE.
</p>

Edit Example

Inlines with !important will take over the other style rules so we see red fonts again.

Similar Tags:

+ more tags