What is CSS specificity?
CSS specificity is how the browser decides which style to apply when multiple CSS rules target the same element.
If you have two rules that both set the color of a paragraph, the browser doesn’t just pick one at random. It calculates a specificity score for each rule and applies the one with the higher score. More targeted selectors win over more general ones.
The scoring works roughly like this: inline styles beat everything. IDs (like #header) score higher than classes and attributes (like .nav or [type="text"]). Classes and attributes score higher than plain element selectors (like p or div). A rule with multiple selectors combines their scores, so .nav .item beats .item on its own.
The !important declaration overrides all of this and forces a style to apply regardless of specificity. It works, but it’s a last resort. Overusing !important makes stylesheets hard to reason about and debug, because you end up fighting your own styles.
Understanding specificity saves a lot of frustration. When a style isn’t applying the way you expect, specificity is usually the culprit.
I specifically remember learning about specificity from CSS Cross Country, a Code School tutorial with a cute skiing theme made by the same people behind Rails for Zombies. Actually learning the rules was one of the most useful things I did early on. A decade later, I still think about it when a style isn’t applying the way I expect.
What I notice now is that a lot of newer engineers skip this entirely. If you’ve only ever used React or another framework that automatically scopes CSS, you can go years without needing to understand specificity. It works until it doesn’t, and then you’re stuck.