CSS !important Rule

What is !important

The !important rule in CSS is used to increase the weight of a style.

!importantRegardless of priority, it is directly related to the final result. When an !important rule is used, this declaration will override any other declaration.

Example

#myid { background-color: blue; } .myclass { background-color: gray; } p { background-color: red !important; }

Try it Yourself »

In the above example, although ID selectors and class selectors have higher priority, the background color of the three paragraphs all displays as red, because the !important rule overrides the background-color property.

Important Notes

Using !important is a bad habit and should be avoided as much as possible, because it breaks the inherent cascade rules in the stylesheet, making debugging and finding bugs much more difficult.

When two conflicting declarations with !important rules are applied to the same element, the declaration with greater priority will be adopted.

In the following example, when viewing the CSS source code, it is not very clear which color is the most important:

Example

#myid { background-color: blue !important; } .myclass { background-color: gray !important; } p { background-color: red !important; }

Try it Yourself »

Usage Suggestions:

  • DefinitelyPrioritize using the priority of style rules to solve problems rather than!important
  • OnlyUse it on specific pages where you need to override site-wide or external CSS.!important
  • NeverUse it in your plugin!important
  • NeverUse it in site-wide CSS code.!important

When to use !important

If you want to set a site-wide style on your website, you can use !important.

For example, if we want all buttons on the website to have the same style:

Example

.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; }

Try it Yourself »

If we place the button in another element with higher priority, the appearance of the button will change, and the properties will conflict, as in the following example:

Example

.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; } #myDiv a { color: red; background-color: yellow; }

Try it Yourself »

If you want to set all buttons to have the same appearance, we can add the !important rule to the button's style property, as shown below:

Example

.button { background-color: #8c8c8c !important; color: white !important; padding: 5px !important; border: 1px solid black !important; } #myDiv a { color: red; background-color: yellow; }

Try it Yourself »
other extensions