View CSS specificity in Chrome DevTools
Which CSS selectors have higher priority? No need to guess, look at their specificity in DevTools!
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.
Have you ever wondered why certain styles in your web page seem to override others? Don't worry, you're not alone! Understanding how CSS determines which rules to apply can be tricky. But guess what? DevTools can help you unravel the mystery!
Let's look at the example above: We begin by inspecting a hyperlink in the DevTools Styles pane. Hovering over the <a>
selector reveals its specificity score of "0, 0, 1". This score acts as a measure of how specific a selector is, determining its dominance in the battle of styles.
The 3 score represents the total of ID, CLASS, TYPE in the selected selector.
Think of it like a game: The higher the score on the left, the more likely that rule wins and decides the final color.
In our case, we see that the color pink has a higher score than yellow because it uses an ID selector (thus scores 1, 0, 0), which is a stronger type of selector.
Now, the fun part: Let's predict what happens with the following CSS, we hover over the hyperlink. Which color will the text and background turn into? We can use our knowledge of selector specificity to make an educated guess.
<style>
a { color: yellow; }
#home-link { color: hotpink; }
div > a.primary: hover { color: rebeccapurple; background: black; }
div > a[role="button"] :hover { background: blue; }
</style>
DevTools to the rescue! We can use DevTools to confirm our prediction. We see that the text remains pink thanks to its high specificity score. However, the background becomes blue because the two hover rules have the same score, and the last rule written in the code wins.
Specificity 1, 0, 0:
#home-link
(winning because its ID score on the left is the highest)Specificity 0, 2, 2:
div > a[role="button"] :hover
(same score as the next one, winning because of its position, it is the last rule)Specificity 0, 2, 2:
div > a.primary: hover
Specificity 0, 0, 1:
a
See? It's not so complicated after all! With DevTools by your side, you can figure out why your styles behave the way they do. You'll be able to predict how different rules interact and create amazing layouts with confidence.
So next time you're struggling with CSS, remember that DevTools is your superpower to crack the code!