Glossary · Beginner

Specificity

Specificity is the weighting a browser uses to decide which CSS declaration wins when several selectors target the same element.

Published
Last checked

Definition

Specificity is how a browser ranks competing CSS declarations. It is counted in three groups: identifiers, then classes and attributes and pseudo-classes, then element and pseudo-element selectors. The higher count wins group by group, starting from the left.

Order only breaks ties

Two declarations of equal specificity are resolved by document order, with the later one winning. This is why "it works if I move it down the file" sometimes holds and sometimes does not. If specificity differs, position is irrelevant regardless of how far down you move the rule.

Inline styles and the important flag

A style attribute outranks selectors in the stylesheet. An !important declaration outranks normal declarations entirely and is resolved on its own level. Both are difficult to override later, which is why each tends to spread once introduced.

Keeping it low on purpose

Flat, class-based selectors keep specificity low and predictable, so components stay overridable. Deep descendant chains raise it invisibly and force every future override to be at least as deep. Modern selectors such as :where() contribute zero specificity and exist precisely for this problem.

Common failures

  • An !important added to defeat an earlier !important.
  • Identifier selectors used for styling rather than for anchors and labels.
  • Long descendant chains copied from developer tools.
  • Utility classes that silently lose to a component rule.
  • A cascade problem misdiagnosed as a build or ordering bug.

Review question

When a rule does not apply, inspect the element and read which declaration won and why. Raising specificity to force a result is usually the moment a stylesheet starts becoming unmaintainable.