CSS !important Rule
What is !important
The !important
rule in CSS is used to increase the weight of a style.
!important
is not related to priority, but it is directly related to the final result. When an !important
rule is used, this declaration will override any other declarations.
Example
#myid {
background-color: blue;
}
.myclass {
background-color: gray;
}
p {
background-color: red !important;
}
In the above example, despite the ID selector and class selector having higher priority, the background color of all three paragraphs will display as red because the !important
rule overrides the background-color
property.
Important Note
Using !important
is a bad habit and should be avoided because it disrupts the inherent cascade rules in style sheets, making debugging and finding bugs more difficult.
When two conflicting declarations with !important
are applied to the same element, the declaration with the higher priority will be adopted.
In the following example, it is not clear which color is most important when looking at the CSS source code:
Example
#myid {
background-color: blue !important;
}
.myclass {
background-color: gray !important;
}
p {
background-color: red !important;
}
Usage Recommendations:
- Always prioritize using the priority of style rules to solve problems rather than
!important
. - Only use
!important
in specific pages where you need to override global or external CSS. - Never use
!important
in your plugins. - Never use
!important
in site-wide CSS code.
When to Use !important
If you want to set a global style for your entire website, you can use !important
.
For example, if you want all buttons on your website to have the same style:
Example
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
If we place the button inside another element with higher priority, the button's appearance will change, and properties will conflict, as shown in the following example:
Example
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
#myDiv a {
color: red;
background-color: yellow;
}
If you want to ensure that all buttons have the same appearance, you can add the !important
rule to the button's style properties, 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;
}