CSS Specificity of *

I’ve been writing CSS for years. Sometimes — ashamed as I am to admit — I get snobby and feel I know it better than the back of my hand. This morning sent a shot of reality with something as simple as CSS specificity. In fact, many developers I work with were also surprised to learn this little bit of knowledge.

First, a quick test. What colour would you expect the child div to be?

div { background: pink; }
div > div { background: blue; }
div > * { background: red; }

As of this morning I thought it would be red. Turns out it’s blue – proof.

Why isn’t it red?

Turns out the * has zero specificity. So div > div has two levels of specificity while div > * only has one.

A simpler example is this:

See the Pen Simple CSS specificity example 2 by Carson Shold (@cshold) on CodePen.

In this case, it doesn’t matter if you switch the order of the selectors in your stylesheet. The div will always be more specific than *, and therefore any div will be lightblue. It’s the same specificity rule as .class being more specific than an element alone, regardless of order in your stylesheet.

Check out this great Specificity Calculator (by Keegan Street) to check your selectors and get a better understanding of CSS specificity.

The best part about learning this is I taught one of my idols about this on Twitter and thought it fun to share.

Leave a Reply