Tutorials CSS Specificity & Cascade
Ch 38 / 60
Chapter 38 Intermediate 10 min read CSS

CSS Specificity & the Cascade

When two CSS rules target the same element and property, which one wins? The answer comes from two algorithms: specificity (which selector is more precise) and the cascade (a broader set of rules including source order, origin, and !important). Understanding both is what separates developers who fight with CSS from those who write it confidently.

What you'll learn
The specificity (A,B,C) model
How to calculate and compare specificity
The cascade — 4 resolution steps
Inheritance — which properties cascade down
!important — when and why not
Cascade layers with @layer

The Specificity Model — (A, B, C)

Specificity is represented as three independent counters. When two rules conflict, the browser compares them column by column, left to right — a higher A always beats any number of B or C:

A
ID selectors
#id
B
Class / Attr / Pseudo-class
.class · [attr] · :hover
C
Element / Pseudo-element
div · p · ::before
Selector
A
B
C
Result
* — universal
0
ID
0
CLS
0
EL
(0,0,0)
p
0
ID
0
CLS
1
EL
(0,0,1)
div p
0
ID
0
CLS
2
EL
(0,0,2)
.btn
0
ID
1
CLS
0
EL
(0,1,0)
a:hover
0
ID
1
CLS
1
EL
(0,1,1)
.nav > a.active
0
ID
2
CLS
1
EL
(0,2,1)
#header
1
ID
0
CLS
0
EL
(1,0,0)
#nav .btn:hover
1
ID
2
CLS
0
EL
(1,2,0)
Key rule — columns don't overflow
Specificity columns are independent. A selector with 100 class selectors never beats even one ID — (0,100,0) loses to (1,0,0). The columns do not carry over. Think of them as three separate numbers compared from left to right — not as a three-digit decimal number.

How to Calculate Specificity

Count each selector type in the full selector expression. Combinators and the universal selector * contribute nothing. Special cases to know:

✓ Count as B (class-level)
  • Class selectors: .btn, .active
  • Attribute selectors: [type="text"], [href]
  • Pseudo-classes: :hover, :nth-child(), :not()*
  • :is(), :has() — takes specificity of most specific argument
  • :where() — always contributes (0,0,0)
Special cases
  • * universal = (0,0,0) — no specificity
  • Combinators (space, >, +, ~) = nothing
  • :not(X) = X's specificity, not :not() itself
  • :where(X) = always (0,0,0) regardless of X
  • inline style="" beats any selector — equivalent to (1,0,0,0)
  • !important overrides everything — handled by cascade, not specificity
CSS — specificity examples with calculations
/* (A, B, C) — count each selector type */

*                      /* (0,0,0) */
p                      /* (0,0,1) — 1 element */
p::first-line          /* (0,0,2) — element + pseudo-element */
div p                  /* (0,0,2) — 2 elements, combinator ignored */
.btn                   /* (0,1,0) — 1 class */
a:hover                /* (0,1,1) — 1 pseudo-class + 1 element */
input[type="text"]     /* (0,1,1) — attr selector + element */
.nav > a.active        /* (0,2,1) — 2 classes + 1 element */
#header                /* (1,0,0) — 1 ID */
#nav .btn:hover        /* (1,2,0) — ID + 2 class-level */

/* :not() — takes specificity of its argument */
a:not(.active)         /* (0,1,1) — .active is (0,1,0) + a is (0,0,1) */
:is(h1, h2, h3)        /* (0,0,1) — max specificity of h1/h2/h3 */
:is(#id, .class)       /* (1,0,0) — takes #id's high specificity! */
:where(h1, h2, h3)     /* (0,0,0) — always zero */

The Cascade — How Browsers Decide

When multiple declarations set the same property on the same element, the browser resolves the conflict using the cascade — a series of steps applied in order. If any step produces a clear winner, it stops there:

1
Origin & Importance
CSS comes from three origins: user-agent (browser default), author (your stylesheet), user (reader's preferences). Normal declarations: author wins over user-agent. But !important declarations reverse this order — user-agent !important beats author !important.
2
Cascade Layers (@layer)
Within the author origin, @layer lets you define explicit ordering. Unlayered styles win over any layer. Within layers, later-declared layers win. This gives you control independent of specificity.
3
Specificity
If same origin and layer — compare specificity (A,B,C). Higher specificity wins. If still tied, move to step 4.
4
Source Order
The last declaration in source order wins. Later stylesheets and rules override earlier ones when everything else is equal.
CSS — cascade examples
/* Step 3: Specificity wins */
p         { color: red; }    /* (0,0,1) — loses */
.intro    { color: blue; }   /* (0,1,0) — wins */

/* Step 4: Source order wins (equal specificity) */
.btn      { color: red; }    /* (0,1,0) — earlier, loses */
.btn      { color: blue; }   /* (0,1,0) — later, wins */

/* The "link state" order LVHA relies on source order */
a:link    { color: blue; }    /* all same specificity */
a:visited { color: purple; }
a:hover   { color: orange; }  /* last → wins when hovered */
a:active  { color: red; }     /* last → wins when active */

Inheritance

Some CSS properties are inherited — when you set them on a parent, all descendants automatically use that value unless they have their own. Others are not inherited — children start from the browser default.

Live demo — color set on parent, all children inherit it
This text is blue — color is set on the parent div.

This <p> also blue — inherits from parent.

This <strong> is orange — it has its own color rule, overriding the inherited value.
This <em> is purple — also overriding locally.

Back to blue — no local override on this p.

✓ Inherited properties
color · font-size · font-family · font-weight · line-height · letter-spacing · text-align · text-indent · visibility · cursor · list-style · word-spacing
✗ Not inherited
background · border · margin · padding · width · height · display · position · float · overflow · box-shadow · transform
CSS — inheritance keywords
/* Explicitly control inheritance */
p    { color: inherit; }    /* force inherit from parent */
p    { color: initial; }   /* reset to browser's default value */
p    { color: unset; }     /* inherits if inherited, else initial */
p    { color: revert; }    /* reverts to browser/user stylesheet default */

/* Reset ALL properties */
.reset  { all: unset; }     /* remove ALL author styles */
.reset  { all: revert; }    /* restore browser defaults */

/* Practical: inherit border-box everywhere */
html     { box-sizing: border-box; }
*, *::before, *::after {
  box-sizing: inherit;  /* inherits border-box from html */
}

/* Practical: base font on body */
body     { font-family: Arial, sans-serif; color: #1e293b; }
/* All descendants inherit font and color automatically */

!important — The Override of Last Resort

!important bypasses specificity entirely for normal declarations. Any !important declaration beats any non-!important declaration, regardless of specificity. When two !important declarations conflict, specificity is used again — but for the !important declarations only.

Without !important — ID (#1,0,0) beats class
ID wins → purple

.imp-btn-normal { color: red } → loses to
#btn-id.imp-btn-normal { color: purple }

With !important — low-specificity class wins
!important wins → green

.imp-btn-important { color: green !important }
wins even against #id { color: red }

CSS — !important rules and usage
/* !important overrides specificity */
#main .content p { color: blue; }         /* (1,1,1) — loses */
p                { color: red !important; } /* (0,0,1) — wins! */

/* Two !important rules — specificity applies between them */
p     { color: red !important; }   /* (0,0,1) !important — loses to ↓ */
.para { color: blue !important; }  /* (0,1,0) !important — wins */

/* ✓ Legitimate uses */
.sr-only  { position: absolute !important; } /* screen reader utility */
.hidden   { display:  none !important; }     /* override any display */
.text-red { color:    red !important; }      /* utility-first (Tailwind) */

/* ✗ Avoid in component styles — leads to !important wars */
.card     { background: white !important; }  /* DON'T — breaks theming */

Cascade Layers — @layer

@layer is a modern CSS feature (all browsers since 2022) that lets you group styles into explicitly ordered layers. Later layers win regardless of specificity, and unlayered styles always win over any layer. This solves the classic problem of specificity wars in large codebases:

Layer priority — lowest to highest (later wins)
1
@layer base
Browser resets, typography defaults
Lowest
2
@layer theme
Colour tokens, spacing scale
↑ higher
3
@layer components
Button, card, modal styles
↑ higher
4
@layer utilities
Single-purpose helpers: .hidden, .sr-only
Highest
★
Unlayered styles
No @layer — wins over any layer
Always wins
CSS — @layer cascade layers
/* Step 1: Declare layer order — later = higher priority */
@layer base, theme, components, utilities;

/* Step 2: Add styles to each layer */
@layer base {
  *, *::before, *::after { box-sizing: border-box; }
  body { font-family: system-ui, sans-serif; }
}

@layer theme {
  :root { --color-primary: #264de4; }
}

@layer components {
  .btn {
    background: var(--color-primary);
    padding: .5rem 1rem;
  }
}

@layer utilities {
  .hidden  { display:  none; }    /* beats any component style */
  .sr-only { position: absolute; }
}

/* Unlayered styles always win (e.g., page-specific overrides) */
.hero .btn { font-size: 1.25rem; }

/* Layer and @import */
@import url("reset.css") layer(base);
@import url("theme.css")  layer(theme);

Best Practices — Writing Predictable CSS

Situation Recommendation Why
Styling components Use class selectors .btn (0,1,0) — easily overridable
Site-wide base Element + :where() Zero specificity — never blocks overrides
Avoid IDs in CSS Use classes instead IDs create (1,0,0) that is hard to beat without !important
Need to override third-party @layer unlayered rules Unlayered always beats any layer
Utility classes Put in the highest @layer Wins over components without !important
Forced override Increase specificity first Add a parent class before reaching for !important
!important Only for utilities, a11y Cannot be overridden — breaks theming and maintenance
LVHA link states Always declare in order All same specificity — source order decides
Free Resource
CSS3 Cheat Sheet — All Properties & Selectors
Complete reference covering specificity, the cascade, !important and @layer with examples.
Download PDF

Try It Yourself

Experiment with specificity conflicts, inheritance, !important and @layer — change selectors and watch which rule wins:

Live Editor
✎ Editor
👁 Preview
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React and Node.js with real projects and placement support.
120+
Chapters
40 hrs
Content
10 Real
Projects
4.9 ⭐
Rating
HTML5CSS3JavaScriptReact.jsNode.jsTailwind CSSAI Tools

Quick Check — Chapter 38

Questions & Answers
No. The three columns (A, B, C) are completely independent — they do not carry over into each other. A selector with 100 class selectors has specificity (0,100,0). A single ID has specificity (1,0,0). When compared:

— Column A: 1 vs 0 → ID wins immediately. The browser stops comparing.
— Columns B and C are never even considered.

The columns are not digits in a three-digit number — they are three separate numbers compared from left to right. This is why (0,100,0) loses to (1,0,0): A=0 vs A=1, ID wins regardless of B and C.

This is why avoiding IDs in CSS is a best practice — they create a specificity level that requires either another ID or !important to override.
The cascade resolves conflicts in this order — if any step produces a clear winner, resolution stops:

1. Origin and Importance: CSS comes from three origins — user-agent (browser default), author (your stylesheets), and user (reader preferences). For normal declarations, author beats user-agent. But !important reverses this: user-agent !important beats author !important.

2. Cascade Layers (@layer): Within the author origin, explicitly declared layers are compared. Later-declared layers win. Unlayered styles always win over any layer.

3. Specificity: If same origin/layer, compare (A,B,C) specificity. Higher specificity wins.

4. Source Order: If everything else is equal, the last declaration in source order wins. This is why the LVHA order matters for link states — all four pseudo-classes have the same specificity, so the one declared last wins.
:is(#id, .class) has specificity (1,0,0) — ID level.

:is() takes the specificity of its most specific argument. Even if the selector currently only matches .class, the entire :is() expression carries the specificity of #id — (1,0,0).

This is a common gotcha. If you write :is(#id, .class, p) a { color: blue }, the selector has specificity (1,0,1) because of the #id inside :is(). Even if the element you're targeting only matches via the p part, the specificity is still (1,0,1).

This is in contrast to :where(), which always contributes (0,0,0) regardless of its arguments — making it ideal for base styles that should never win a specificity battle.
These are CSS-wide keywords that control how property values are resolved:

inherit — forces the property to take the computed value of the same property on its parent element, regardless of whether it would normally be inherited. Useful for non-inherited properties like border.

initial — resets the property to its CSS specification default value (not the browser stylesheet). For color, the initial value is black according to the spec (not whatever the browser default is).

unset — acts like inherit for inheritable properties and like initial for non-inherited ones. A convenient "smart reset."

revert — rolls the property back to the browser (user-agent) stylesheet value, not the CSS spec initial value. For example, display: revert on a <div> restores display: block (browser default), not display: inline (spec initial).
In large codebases without layers, specificity conflicts accumulate: a component has (0,1,0), a state modifier needs (0,2,0), a parent context adds (0,3,0), then someone adds an ID for urgency (1,0,0), and finally !important wars break out.

@layer solves this by making layer order the primary resolution factor — above specificity:

— Define layers: @layer base, theme, components, utilities;
— Styles in utilities layer always win over components, even with lower specificity
— A utility .hidden { display: none } with (0,1,0) beats a component #card { display: flex } with (1,0,0)

Within each layer, normal specificity still applies. This means you can write low-specificity selectors in utility layers and still have them win over high-specificity selectors in component layers — without !important.

Unlayered styles always win over any layer, providing an easy escape hatch for page-specific overrides.
Multiple Choice Questions
Question 1 of 5
What is the specificity of .nav > ul > li > a:hover?
Question 2 of 5
Two rules both target the same element and property with !important. How is the conflict resolved?
Question 3 of 5
Which property keyword resets a value to the browser's default (user-agent stylesheet) rather than the CSS specification default?
Question 4 of 5
Given @layer base, components, a rule in components has specificity (0,1,0) and a rule in base has specificity (1,0,0). Which wins?
Question 5 of 5
Which CSS property is NOT inherited by default?
Chapter Summary
  • Specificity (A,B,C): A = IDs, B = classes/attributes/pseudo-classes, C = elements/pseudo-elements. Columns are independent — (1,0,0) beats (0,100,0). Combinators add nothing.
  • :is() specificity = most specific argument. :where() = always (0,0,0). Use :where() for base styles that should never block overrides.
  • The 4 cascade steps: 1) Origin + importance, 2) @layer, 3) Specificity, 4) Source order. First step to produce a winner stops the process.
  • Inheritance: Typography properties (color, font-*) inherit down the tree. Box model properties (margin, padding, border, background) do not. Use inherit, initial, unset, revert to control it explicitly.
  • !important: Beats all non-!important declarations. When two !important rules conflict, specificity is used between them. Avoid in component styles — legitimate uses: utilities, a11y overrides.
  • @layer: Later-declared layers win over earlier layers regardless of specificity. Unlayered styles always beat any layer. Enables predictable CSS architecture without specificity wars.
  • Best practices: Use class selectors for components. Avoid IDs. Use :where() for base styles. Put utilities in the highest layer. Prefer increasing specificity over !important.
~10 min read
Intermediate level
Chapter 38 of 60

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel