Advanced20 min read

Specificity & Cascade

Understand how the CSS cascade decides which styles win when multiple rules target the same element. Learn to calculate specificity and use it to your advantage.

The Cascade Algorithm

When multiple CSS rules target the same element, the browser must decide which declaration wins. This decision process is called the cascade, and it follows a strict priority order:

  1. Origin and importance — User-agent (browser) styles < author styles < !important author styles.
  2. Specificity — More specific selectors override less specific ones.
  3. Source order — When specificity is equal, the rule that appears last in the stylesheet wins.

Understanding the cascade is the key to debugging CSS. When a style does not apply as expected, the answer is almost always that another rule with higher specificity or later source order is overriding it.

Calculating Specificity

Specificity is calculated as a three-part score, often written as (A, B, C):

ComponentWhat countsExample
A — ID selectorsEach #id adds 1#header = (1, 0, 0)
B — Class selectors, attribute selectors, pseudo-classesEach .class, [attr], :hover adds 1.nav.active = (0, 2, 0)
C — Element selectors, pseudo-elementsEach div, ::before adds 1ul li a = (0, 0, 3)

Inline styles (the style attribute on an element) beat all selector-based rules. And !important overrides everything, including inline styles.

Examples

  • p = (0, 0, 1)
  • .card = (0, 1, 0)
  • #main .card p = (1, 1, 1)
  • div.container > ul li.active a:hover = (0, 3, 3)

A single ID selector (1, 0, 0) always beats any number of classes (0, N, 0) because the A column is compared first.

Specificity in Practice

html
<style>
  /* Specificity: (0, 0, 1) */
  p {
    color: black;
  }

  /* Specificity: (0, 1, 0) — wins over element selector */
  .highlight {
    color: orange;
  }

  /* Specificity: (1, 0, 0) — wins over class selector */
  #special {
    color: red;
  }

  /* Even 3 classes (0, 3, 0) cannot beat 1 ID (1, 0, 0) */
  .container .highlight .text {
    color: green;
  }
</style>

<div class="container">
  <p class="highlight text" id="special">
    What color am I? (Answer: red)
  </p>
</div>

Which selector has the highest specificity?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.