liveBook · Manning

Specificity

As explained in Web Design Playground, Second Edition

CSS specificity is the ranking assigned to a selector that determines its precedence among competing style rules targeting the same element.

When several CSS rules target the same element, the cascade needs a tiebreaker. Specificity ranks selectors by how precisely they target that element: the more specific selector gets greater weight. section 19.14 section 19.11

Use this quick recipe to compare selectors:

  • Count IDs, classes or pseudo-classes, and elements or pseudo-elements. The familiar I-C-T score records them in that order. section 19.14
  • For the point-style shortcut, give each element or pseudo-element 1 point and each class or pseudo-class 10 points; IDs carry greater weight. section 19.14
  • Compare scores from left to right: 1-0-0 beats 0-1-1, while 0-2-1 beats 0-1-4. section 19.14
  • Remember that specificity applies when declarations come from the same source; !important overrides other sources. section 19.14 section 19.15

A small CSS showdown

For a paragraph with class colored-text inside a div, p.colored-text scores 11 points, .colored-text scores 10, div p scores 2, and p scores 1. The browser therefore applies the first rule, rendering the text purple. section 19.14

<style>
    p.colored-text {
        color: purple;
    }
    .colored-text {
        color: blue;
    }
    div p {             #1
        color: green;
    }
    p {                 #2
        color: red;
    }
</style>
<div>
    <p class="colored-text">What is the color of this text?</p>
</div>

Inspect the competing rules and predict the winning color before checking the specificity scores. section 19.14

How Web Design Playground, Second Edition covers it

How deep it goes
Explains selector scoring with I-C-T comparisons and worked rules, while leaving the wider cascade as surrounding context.
Examples
Uses competing p, class, descendant, and combined selectors to calculate scores and determine a paragraph’s rendered color.
What it assumes
Assumes familiarity with CSS rules and selectors while situating specificity alongside the cascade and inheritance.
What you can do after
Diagnose which competing CSS selector wins by calculating and comparing its specificity.
How it connects
Connects specificity to CSS selectors, cascading, inheritance, inline styles, IDs, classes, pseudo-classes, and !important.

Also explained in

Compare how 6 books explain specificity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Design Playground, Second Edition. The section links point to the parts of the book it draws on.