Heads up: I know what some of you are thinking, but it is not the “elegant” !important css declaration. wink.

As most full stack professionals, I’ve been writing CSS for as long as I can remember, usually indirectly via a higher level language such as SASS. I actually got along pretty well without ever really being bothered by CSS’ specificity rules, until recently when at a web development course I am teaching I had no choice but to finally dive in.

So without further ado… here it is.


CSS Specificity

This topic sounds very complex and daunting, but as it turns out it is extremely simple and actually clarifies a lot and sits well with our developer gut feelings and hunches we went by until now.

Put in simple words, it defines a simple set of rules by which the browser calculates and weighs two CSS selectors one versus the other, in order and decide which one takes becomes effective.Here is a simple graphical chart showing the CSS specificity precedence rules:

CSS Specificity Rules Chart


A Concrete Example

Let’s take the following case:

#widget { // 1 ID
    background-color: yellow;
}

ul li > div.class-a.class-b { // 3 HTML elements + 2 classes
    background-color: green;
}

Assuming both selectors target the same element, its background-color will be yellow and not green, despite their cascading order. If we look at the specificity table above we can see that having an ID (one or more) will always take precedence over a selector without any ID. In this case, the fact that the latter selector has two classes and three HTML elements does not help it win over the former selector.


Final Notes & Conclusions

  • The more specific our selector is the higher its weight (e.g. a selector having three classes will win a selector with two classes)
  • A more specific selector takes over a less specific one, regardless of the order in which they appear
  • When two selectors have the same specificity, the one that comes second (in order of loading) wins
  • !important always has highest precedence
  • Inline styles have second highest precedence
  • The universal selector (*) has zero weight


Now that you know the CSS specificity rules, don’t let !important cramp your style!

Zacky