How CSS Specificity Is Calculated

Why Specificity Exists

When two CSS rules target the same element with conflicting values, the browser needs a way to decide which one wins. Specificity is that scoring system: it ranks selectors by how precisely they target an element, and the highest-scoring rule is applied.

The Specificity Scale

Specificity is commonly written as three numbers, often shown as (A, B, C):

CategorySelectors countedWeight
AID selectors (#id)Highest
BClasses, attribute selectors, pseudo-classes (.class, [type], :hover)Middle
CType selectors and pseudo-elements (div, ::before)Lowest

Inline styles outrank all of these, and !important outranks inline styles - though both are usually best avoided since they make overriding a style later much harder.

Worked Examples

/* (0, 0, 1) - one type selector */
p { color: blue; }

/* (0, 1, 0) - one class selector: wins over the rule above */
.note { color: green; }

/* (0, 1, 1) - one class + one type: wins over a class alone */
p.note { color: purple; }

/* (1, 0, 0) - one ID: wins over everything above */
#warning { color: red; }

When Specificity Is Equal

If two selectors have exactly the same specificity score, the rule that appears later in the stylesheet (or later in the cascade order) wins. This is why the order rules are written in a file can matter just as much as how specific they are.

Keeping Specificity Manageable

  • Prefer classes over IDs for styling, saving IDs for unique landmarks or scripting hooks.
  • Avoid deeply nested selectors that stack up specificity unnecessarily.
  • Avoid !important except as a last resort - it breaks the normal cascade and is hard to override later.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.