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.

| LIVE PREVIEW
  • 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.)

Selectorsno. of #id matchesno. of .class matchesno. of type matches
h1--1
h1 + p::first-letter--3
li > a[href*="en-US"] > .inline-warning-22
#identifier100
#footer :not(nav) li102

Using !important

You should use !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