Most of the time I have seen developers using !important
in css without any necessity. Using !important
just for a simple override is always a bad practice. This is because it makes debugging more difficult by breaking the natural cascading in your stylesheets.
You might be asking, "then how do I avoid it"?
Answer is, you can do it using greater "specificity".
For the next few minutes I am going to explain CSS specificity in the shortest way possible.
CSS specificity is the value provided to each selector so that the browser can understand how much priority to be given to a specific selector.
Below are the selector types in decreasing priority order. The top one having the highest priority and the bottom one has the lowest.
-
!important
- this one is given the highest priority, overriding everything else, including inline styles (style
attribute). If there are multiple CSS selectors with!important
mentioned for same element, the last declaration found in the CSS is applied to the element.
h1 {
color: blue !important
}
-
Inline styles
<h1 style="color: red">Hello reader</h1>
-
ID Selector
#headline {
color: green
}
-
Class, pseudo class and attribute selector
// class selector
.headline {
color: red
}
// pseudo class selector
h1:hover {
color: red
}
// attribute selector
[type="input"] {
color: red
}
-
Type Selectors and pseudo elements
// type selector
h1 {
color: red
}
// pseudo element selector
h1:before {
color: red
}
Other than the above type of selectors there are Universal selectors *
, combinators +
, >
, ~
, ' '
, ||
and negation pseudo-class :not()
which does not have any specificity value.
Now we need to know how the browser calculates the specificity value and what happens when they are combined. The total value for a given combination of selectors is calculated by the priority of the selectors present and the number of occurrence of that selector. You can visualize it from the below image.
Here we have 2 elements body
and div
and 2 classes parentClass
and ChildClass
. That is why we get 2 in each selectors position, because number of occurrences are added along with priority.
You can check this for more examples.
For more details, you can refer this
If you have reached here, I hope you will be able to avoid !important
and use higher specificity instead.
Thank you, happy styling!
Top comments (1)
Avoid specificity by using a system like BEM or even use
!important!important
π€£ yes that works