CSS Specificity: Who Wins the Style Battle?

When multiple CSS rules target the same element and property, which one gets applied? That’s where specificity comes in.

Let’s say you have this HTML and CSS rules:

Code Block Loading...

Which rule wins? The one with higher specificity. If two rules have equal specificity, the one that appears later in the stylesheet wins.

How Specificity Is Calculated

CSS uses a four-part scoring system to calculate specificity. Think of it like a four-digit number: Inline styles → IDs → Classes → Elements

Each rule gets a score like a b c d:

  • a → Inline styles
  • b → ID selectors
  • c → Class, attribute, and pseudo-class selectors
  • d → Element and pseudo-element selectors

Element Selectors (d slot)

Each tag name adds 1 to the last slot:

Code Block Loading...

Class, Attribute, and Pseudo-Class Selectors (c slot)

Each class, attribute, or pseudo-class adds 1 to the third slot:

Code Block Loading...

You can even repeat classes to increase specificity:

Code Block Loading...

ID Selectors (b slot)

ID selectors are powerful and add 1 to the second slot:

Code Block Loading...

Inline Styles (a slot)

Inline styles override all external or internal CSS:

Code Block Loading...

!important Overrides Everything

If a rule uses !important, it ignores specificity and wins unless another !important rule has higher specificity.

Code Block Loading...

Use !important sparingly. It’s a last resort, not a best practice.

Best Practices

  • Use just enough specificity to target elements cleanly.
  • Avoid overusing id selectors—they’re hard to override.
  • Prefer classes for reusable, flexible styling.
  • Avoid !important unless debugging or overriding deeply nested styles.

Specificity Calculator Tool

Need help calculating specificity? Try this tool: 🔗

specificity.keegan.st

It’s a great way to visualize how your selectors stack up.