CSS !important Rules


What is !important

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

!important has nothing to do with priority, but it is directly related to the final result. When an !important rule is used, this statement will override any other statement.

Example

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

 Try It! 

In the above example, although the ID selector and the class selector have higher priority, the background colors of the three paragraphs are all displayed in red because the !important rule will override the background-color property.

Important

Using !important is a bad habit and should be avoided as much as possible, because it breaks the inherent cascade rules in the style sheet and makes it more difficult to debug and find bugs.

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

In the following example, when we look at the CSS source code, we are not very clear about which color is the most important:

Example

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

 Try It! 

Suggestions:

  • Be sure to give priority to using the priority of style rules to solve the problem instead of !important

  • Only use (!important) in specific pages that need to cover the entire site or external CSS

  • Never use it (!important) in your plugin

  • Never use it (!important) in site-wide CSS codes

When to use !important

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

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

Example

.button {

   background-color: #9a9a9a;

   color: white;

   padding: 5px;

   border: 1px solid black;

}

 Try It! 

If we put the button in another element with a higher priority, the appearance of the button will change, and the attributes 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! 

If we want to set all buttons to have the same appearance, we can add the !important rule to the button's style attribute, 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!