DevAcademy
LearnCSSSpecificity & the Cascade
IntermediateCSS

Specificity & the Cascade

Understand how CSS decides which rule wins when multiple rules target the same element.

Reading Time

16 min

Lesson

Lesson 20 of 30

Why Specificity Matters

When more than one CSS rule matches the same element and sets the same property, the browser must decide which one to apply. This decision is based on specificity, source order, and importance.

A Specificity Conflict

<style>
  p { color: blue; }
  .note { color: green; }
  #warning { color: red; }
</style>

<p id="warning" class="note">
  This text is red — the ID selector wins.
</p>
Output

How Specificity is Calculated

Specificity is often represented as three numbers, from most to least powerful: ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors. More of a stronger category always beats any amount of a weaker one.

Specificity Categories (Strongest to Weakest)

CategoryExamplesWeight
Inline stylestyle="color: red"Highest (beats all selectors)
ID selectors#header1-0-0
Classes, attributes, pseudo-classes.btn, [type="text"], :hover0-1-0
Type selectors, pseudo-elementsdiv, ::before0-0-1

Comparing Specificity

/* 0-0-1 */
p { color: black; }

/* 0-1-0 — wins over the type selector above */
.highlight { color: orange; }

/* 1-0-0 — wins over both rules above */
#unique { color: purple; }

Source Order

When two rules have equal specificity, the one that appears later in the stylesheet wins. This is the "cascading" part of Cascading Style Sheets.

Equal Specificity, Order Decides

<style>
  .box { color: blue; }
  .box { color: green; } /* wins — same specificity, comes later */
</style>

<p class="box">This text is green.</p>
Output

The !important Escape Hatch

Adding !important to a declaration overrides normal specificity rules almost entirely. It should be used sparingly — overusing it makes styles unpredictable and hard to override later, often forcing more !important rules to fix.

Best Practice

Keep selectors as low-specificity as possible (favor classes over IDs and deep nesting) so later overrides stay easy, and avoid !important except as a last resort.

Interview Questions

Quick Quiz

1. Which of these has the highest specificity?

2. When two rules have equal specificity, which one wins?

3. Why should !important be used sparingly?