DevLab
CSS

CSS Specificity: Why Your Styles Aren't Applying

Understand how CSS specificity works, how to calculate it, and how to avoid the !important trap.

What is CSS Specificity?

When multiple CSS rules target the same element, the browser needs to decide which one wins. Specificity is the weighting system CSS uses to resolve these conflicts. Higher specificity wins.

Specificity is calculated as a three-column score: (ID, Class/Attribute/Pseudo-class, Element/Pseudo-element).

Specificity Values

  • Inline styles: (1, 0, 0, 0) — highest weight
  • ID selectors #id: (0, 1, 0, 0)
  • Class .class, attributes [attr], pseudo-classes :hover: (0, 0, 1, 0)
  • Type selectors div, pseudo-elements ::before: (0, 0, 0, 1)
  • Universal selector *: (0, 0, 0, 0)

Calculating Specificity

#nav .item:hover = 1 ID + 1 class + 1 pseudo-class = (0, 1, 2, 0)

header nav ul li a = 5 elements = (0, 0, 0, 5)

The first selector wins because it has an ID component.

The !important Rule

!important overrides all other specificity calculations. It should be a last resort — once you start using it, you end up in specificity wars that make CSS unmaintainable.

Better alternatives: Use more specific selectors, restructure your CSS, or use CSS custom properties.

Practical Tips

  • Keep selectors as short as possible — over-qualified selectors cause maintenance headaches
  • Avoid ID selectors for styling — IDs are too specific and can only be used once per page
  • Use BEM naming or CSS modules to avoid conflicts
  • Use the DevLab Specificity Calculator to debug conflicting rules

Practice with these tools

More Learning Topics