13
Stop using '!important' in css - css specificity explained in shortest possible way
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.
If you have reached here, I hope you will be able to avoid !important
and use higher specificity instead.
Thank you, happy styling!
13