I’m Jecelyn Yeen, currently working on Chrome Tooling - Chrome DevTools, Puppeteer and more at Google. I tend to talk about web development, debugging & testing.
Prefer video over text? Head to the end for the video version.
Ever confused about which CSS style wins out when there are multiple rules? Understanding how to calculate the weight of a CSS selector is crucial for determining which style reigns supreme.
This weight, known as specificity, boils down to three key numbers: ID, class, and type. It's like a scorecard for each selector, telling us who gets to be the boss of your element's style.
Let's break down each selector.
div > a.primary:hover
Take div a.primary:hover
as an example. It has a score of 0, 2, 2.
0 - No IDs
2 - Two classes -
.primary
and the:hover
2 - Two types -
<div>
and<a>
div > a[role=”button”]:hover
Remember, attribute selectors like [role="button"]
count as classes as well! So, replacing .primary
with [role="button"]
doesn't change the score.
0 - No IDs
2 - Two classes -
[role="button"]
and the:hover
2 - Two types -
<div>
and<a>
#home-link
Now, look at #home-link
. That one ID gives it a score of 1, 0, 0.
1 - ID -
#home-link
0 - No classes
0 - No types
The rules
The higher the score on the left, the stronger the selector: So, even if you have lots of classes and types, an ID will always win. It's like having the royal flush in a poker game!
The position matters too, last one wins: Given two selectors with same scores across 3 numbers, then whichever come last wins.
Let’s put practice with a few examples.
Is the border dash, double or solid?
Given the following CSS, is the border dash, double or solid?
<style>
#home-link { border: solid; }
div > a.primary:hover { border: dashed; }
div > a[role="button"]:hover { border: double; }
</style>
The border is solid because rule #1 applies - The higher the score on the left, the stronger the selector.
Is the color blue or red?
How about the following CSS? Is the hyperlink red or blue?
<style>
div > a.primary:hover { color: red; }
div > a[role="button"]:hover { color: blue; }
</style>
The color is blue. Both selectors have the same score 0, 2, 2. However, remember our rule #2 - The position matters too, last one wins. Since div > a[role="button"]:hover
comes last, so it wins.
Do I need to calculate manually? 😱
No worries, you don’t have to. You can view the score in the Chrome DevTools Styles tab! Find out more in my previous blog post.
By the way, there are more rules if…
If you use the new CSS Cascade Layers a.k.a the @layer CSS rule. It’s something advanced. We’ll discuss that in the future, you can check out the links in the meantime.