Specificity and !important
Basically, CSS rules cascade and rules specified later will override rules specified earlier.
However, different kinds of selector matches have different "weights" to them. In descencing order of priority/specificity:
- Any rules in
style="..."
attribute has the top priority, then - The number of
#id
selector matches, then - The number of
.class
selector matches (including[attr]
and:pseudoclass
), then - The number of
type
selector matches (including::pseudoelement
).
So, after style="..."
rules, it goes ID > class > type.
- Whiskey and Ginger Ale
- Wheat Beer
- Mint Julip
Specificity Calculation Example
Here's an example on how the number of match is calculated.
Note that the universal selector (*
), combinators (" ", >
, ~
, +
, ||
), and the :not(...)
pseudo-class has no effect on specificity. (The selectors inside :not(...)
do, however.)
Selectors | no. of #id matches | no. of .class matches | no. of type matches |
---|---|---|---|
h1 | - | - | 1 |
h1 + p::first-letter | - | - | 3 |
li > a[href*="en-US"] > .inline-warning | - | 2 | 2 |
#identifier | 1 | 0 | 0 |
#footer :not(nav) li | 1 | 0 | 2 |
Using !important
!important
sparingly (e.g. to override third-party CSS). It will get ugly if everything starts to need !important
to work.If any CSS rule has the !important
declaration (e.g. color: red !important;
), then it "overrule
all of the above calculations" and take the top priority.
Then, if multiple rules with !important
clashes, refer to the calculations above to see which !important
wins.
References
- Specificity (MDN) — https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
- Specifics on CSS Specificity (CSS-Tricks) — https://css-tricks.com/specifics-on-css-specificity/