CSS !important Rule
- Previous Page CSS Specificity
- Next Page CSS Mathematical Functions
What is !important?
In CSS !important
Rule is used to give the attribute/value a higher priority than normal styles.
In fact, if you use !important
Rule, which will override all previous style rules for the specific property on the element!
Let's look at an example:
Example
#myid { background-color: blue; } .myclass { background-color: gray; } p { background-color: red !important; }
Example explanation
In the above example, all three paragraphs will have a red background color, despite the ID selector and class selector having higher specificity.!important
The rule overrides the background-color property in both cases.
Important points about !important
Override !important
The only way to override the rule is to include another declaration with the same (or higher) specificity in the source code of !important
Rule - this is the beginning of the problem! It makes the CSS code confusing and debugging difficult, especially when you have a large stylesheet!
Here we create a simple example. When you view the CSS source code, it is not clear which color is considered the most important:
Example
#myid { background-color: blue !important; } .myclass { background-color: gray !important; } p { background-color: red !important; }
Tip:Understand !important
The rule is good. You may see it in some CSS source code. However, unless you absolutely must use it, do not use it.
There may be one or two reasonable uses of !important
One use !important
The situation is, if you must override styles that cannot be overridden in any other way. This may be because you are using a content management system (CMS) and cannot edit CSS code. Then you can set some custom styles to override certain CMS styles.
Another use !important
The situation is: suppose you want all buttons on the page to have a special appearance. Here, the button style is gray background color, white text, and some padding and border:
Example
.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; }
If we place the button within another element with higher specificity, the appearance of the button may change, and properties may conflict. Here is an example:
Example
.button { background-color: #8c8c8c; color: white; padding: 5px; border: 1px solid black; } #myDiv a { color: red; background-color: yellow; }
To 'force' all buttons to have the same appearance at all times, we can set !important
Rules are added to the properties of the button, 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; }
- Previous Page CSS Specificity
- Next Page CSS Mathematical Functions