Chapter 06 of 33

Specificity, Inheritance & the Cascade

So far you have learned many ways to select an element: type selectors, classes, IDs, combinators, attribute selectors, pseudo-classes. Very soon you will hit a situation like this: two rules select the same element and set the same property to different values. Which one does the browser use?

Many beginners guess "the last one written wins". Sometimes that is true, often it is not, and that is where hours of "why is my CSS not working?" debugging come from. In this chapter we will learn the exact rules the browser follows: the cascade, specificity and inheritance. These three ideas are what the "C" in CSS is about, and they are a favourite topic in front-end interviews.


The Problem: Conflicting Declarations

Look at this small page:

<div class="box">
  <p class="note">Which colour am I?</p>
</div>
.box p  { color: green; }
div > p { color: orange; }
.note   { color: purple; }
p       { color: gray; }

All four rules match the paragraph, and all four set color. The paragraph is displayed in green, even though the green rule is written first. By the end of this chapter you will be able to explain exactly why, and calculate the answer for any such conflict.

The cascade is the algorithm the browser uses to choose one winning value when several declarations set the same property on the same element.


The Cascade Step by Step

When several declarations compete, the browser compares them using a list of criteria, in order. It moves to the next criterion only if the current one is a tie.

StepCriterionSimple meaning
1RelevanceOnly declarations whose selector matches the element (and whose @media / @supports conditions are true) take part.
2Origin and importanceWho wrote the rule (browser, user, author) and whether it has !important.
3ContextRelevant only with Shadow DOM (web components); you can ignore it for normal pages.
4Element-attached stylesDeclarations in a style="..." attribute beat rule-based declarations of the same origin and importance.
5Cascade layersRules inside @layer blocks are ordered by layer.
6SpecificityThe more specific selector wins.
7Scope proximityOnly for rules inside @scope: the closer scope root wins.
8Order of appearanceIf everything else is equal, the declaration that comes last wins.

For everyday work you mainly deal with four of these: origin/importance, inline styles, specificity and order of appearance. Layers and scope are newer tools for organising large style sheets. We will cover each in turn.

A simplified mental model that is good enough for most exam answers:

!important  >  inline style  >  higher specificity  >  later in source

Step 2: Origin and Importance

CSS can come from three origins:

  • User-agent styles: the browser's built-in default style sheet. This is why <h1> is big and bold, and why <body> has an 8px margin even with no CSS of your own.

  • User styles: styles set by the person using the browser, for example through accessibility settings or an extension that forces large text.

  • Author styles: the CSS written by the website developer, which means you.

A declaration can also be marked !important, which moves it into a separate, stronger group. The full precedence, from lowest to highest, is:

Precedence (low → high)Origin / importance
1User-agent, normal
2User, normal
3Author, normal
4CSS keyframe animations
5Author, !important
6User, !important
7User-agent, !important
8CSS transitions

Notice the interesting flip: for normal declarations the author beats the user, but for !important declarations the user beats the author. Why? So that a person with low vision who forces a large font with !important cannot be overridden by a website. Accessibility comes first.

Using !important

.note { color: purple !important; }
#intro { color: blue; }

Even though #intro is far more specific, the !important declaration wins, because importance is checked before specificity.

!important is a sledgehammer. Once you use it, the only way to override that declaration is another !important declaration that wins the cascade (for example, one with higher specificity, or equal specificity and later in the source), and very soon your style sheet becomes a war of !importants. Reasonable uses are rare: utility classes that must always win (like .hidden { display: none !important; }), or overriding third-party CSS you cannot edit.


Step 4: Inline Styles

A declaration written in the style attribute is attached directly to the element:

<p class="note" style="color: rgb(9, 9, 9)">Inline wins</p>

It beats every normal author rule from your style sheets, no matter how specific the selector, even #main #content p.note. Only !important author rules (and the higher rows in the table above) can beat it.

Older tutorials describe inline styles as having specificity "1,0,0,0". That is a useful way to remember that they beat any selector, but strictly speaking modern CSS treats inline styles as their own cascade step, not as part of specificity. Either way the result is the same.


Step 6: Specificity

Specificity is a score calculated from a selector that measures how precisely it targets an element. When two declarations have the same origin, importance and layer, the one whose selector has higher specificity wins.

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

ColumnCountsExamples
AID selectors#header, #intro
BClass selectors, attribute selectors, pseudo-classes.btn, [type="text"], :hover, :nth-child(2)
CType (element) selectors and pseudo-elementsp, div, ::before, ::first-line
(none)Universal selector and combinators add nothing*, >, +, ~, space

How to compare two specificities

Compare column A first. Whoever has the larger A wins, and you stop there. Only if A is equal do you compare B, and only if B is equal do you compare C. If all three are equal, specificity is a tie and the cascade moves on to order of appearance.

This is exactly like comparing version numbers or dates (year, then month, then day). It is not a base-10 number. One ID beats any number of classes:

#intro { color: blue; }                           /* (1, 0, 0) */
p.lead.big.x.y.z.a.b.c.d.e.f { color: red; }      /* (0, 11, 1) */

The paragraph matched by both is blue. Eleven classes do not "carry over" into the ID column. We checked this in Chrome: the computed colour is rgb(0, 0, 255).

Worked examples

Let's calculate step by step. Read the selector left to right and count each simple selector into its column.

SelectorIDs (A)Classes / attributes / pseudo-classes (B)Types / pseudo-elements (C)Specificity
p001 (p)(0, 0, 1)
ul li a003(0, 0, 3)
.note010(0, 1, 0)
div > p002(0, 0, 2)
.box p011(0, 1, 1)
a[href^="https"]01 (attribute)1(0, 1, 1)
li:first-child::before01 (:first-child)2 (li, ::before)(0, 1, 2)
#nav .menu a:hover12 (.menu, :hover)1(1, 2, 1)
* > *000(0, 0, 0)

Now go back to the opening puzzle:

.box p    → (0, 1, 1)   ← highest
.note     → (0, 1, 0)
div > p   → (0, 0, 2)
p         → (0, 0, 1)

.box p and .note tie in column A (0) and column B (1), so column C decides: 1 beats 0. The paragraph is green. Chrome agrees: rgb(0, 128, 0), the value of the keyword green.

Special pseudo-classes: :is(), :not(), :has() and :where()

You met these in the chapter Pseudo-classes & Pseudo-elements. Their specificity follows special rules:

  • :is(), :not() and :has() do not count themselves. Instead they take the specificity of their most specific argument, even if a less specific argument is the one that actually matched.

  • :where() always has specificity (0, 0, 0), whatever is inside it. This makes it perfect for default styles that should be easy to override.

  • :nth-child(An+B of S) counts as one pseudo-class plus the most specific selector in S. So :nth-child(2 of .item) is (0, 2, 0).

:is(#zz, .q) { color: teal; }   /* (1, 0, 0): takes #zz's specificity */
.q.r         { color: navy; }   /* (0, 2, 0) */

:where(#t3)  { color: red; }    /* (0, 0, 0) */
#t3          { color: black; }  /* (1, 0, 0) */
<p class="q r">I am teal</p>
<p id="t3">I am black</p>

The first paragraph has no element with id="zz" anywhere, it matches :is() only through .q. Still the rule scores (1, 0, 0) and beats .q.r, so the text is teal. This surprises many people, and it makes a good interview question.


Step 8: Order of Appearance

When origin, importance, layer and specificity are all equal, the declaration that appears later wins.

.order1 { color: crimson; }
.order2 { color: seagreen; }
<p class="order2 order1">Hello</p>

The text is seagreen. The order of classes inside the class attribute does not matter at all; only the order of the rules in the CSS matters.

"Later" means later in the final combined order of all style sheets. If your page has:

<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="my-styles.css">

then your rules in my-styles.css come later and win ties against Bootstrap's. Swap the two lines and Bootstrap wins the ties. A <style> block is placed in this order according to where it appears in the document.

Inside a single rule, the same idea applies to repeated properties. Developers use this for fallbacks:

.title {
  color: rgb(200, 0, 0);          /* used by very old browsers */
  color: oklch(0.55 0.2 25);      /* newer browsers understand this and it wins */
}

A browser that does not understand the second value ignores that declaration completely (as you learned in Introduction to CSS), so the first one stays.


Step 5: Cascade Layers (@layer)

In big projects, fighting specificity becomes painful: a reset file, a framework, component styles and utility classes all compete. Cascade layers let you decide the priority of whole groups of rules up front. @layer has been supported in all major browsers since 2022.

/* Declare the order once: later layers win */
@layer base, theme;

@layer theme {
  .lay { color: rgb(1, 1, 1); }
}
@layer base {
  #lay { color: rgb(2, 2, 2); }     /* high specificity, but in a weaker layer */
}

p { color: gray; }                  /* not in any layer */
<p class="lay" id="lay">Which colour?</p>

Reasoning:

  1. Between the two layered rules, theme was declared after base, so theme wins even though #lay has an ID. Layer order is checked before specificity.

  2. But the plain p rule is unlayered, and for normal declarations unlayered styles beat all layers.

So the paragraph is gray, even though p has the lowest specificity of all three. Chrome confirms rgb(128, 128, 128).

For !important declarations the layer order is reversed: an !important rule in an earlier layer beats one in a later layer, and both beat an unlayered !important rule. This mirrors the origin flip you saw earlier: lower-priority layers get the final say when they mark something important.

DeclarationsWho wins
NormalUnlayered > last declared layer > … > first declared layer
!importantFirst declared layer > … > last declared layer > unlayered

We will use layers again in the chapter CSS Architecture & BEM. For now, remember the key idea: layer beats specificity.

Scope proximity (@scope) is the newest step. It only applies to rules written inside @scope blocks, and it reached Baseline (support in all major browsers) only in 2026, so treat it as a newer, optional tool and check browser support before relying on it.


Inheritance

The cascade decides between declarations that exist for an element. But what if no rule sets a property on an element at all? Then one of two things happens:

  • If the property is inherited, the element takes its parent's computed value.

  • If the property is not inherited, the element gets the property's initial value (its default from the specification).

Inheritance is the mechanism by which some CSS properties pass their computed value from a parent element down to its children when the children don't specify a value themselves.

This is why you can write body { font-family: Arial; } once and every paragraph, list and heading uses Arial.

.parent {
  color: rgb(10, 20, 30);
  font-size: 20px;
  border: 2px solid red;
}
<div class="parent">
  <span class="child">Child text</span>
</div>

The span gets color: rgb(10, 20, 30) and font-size: 20px from its parent, but its border width is 0px: borders are not inherited. That is a good design decision; imagine if every child inside a bordered box also drew its own border!

Which properties inherit?

The rule of thumb: text-related properties inherit, box-related properties don't.

Usually inheritedNot inherited
colorbackground-color, background-image
font-family, font-size, font-weight, font-stylewidth, height
line-height, letter-spacing, word-spacingmargin, padding, border
text-align, text-indent, text-transformdisplay, position, top/left
visibility, cursoroverflow, opacity
list-style, white-spacebox-shadow, transform

The specification of every property has an "Inherited: yes/no" line, and MDN shows it in each property's "Formal definition" section.

Note that background-color is not inherited, but a child usually looks like it has the parent's background. That is because its own background is transparent (the initial value), so you see the parent's background through it.

Inherited values lose to any matching rule

An inherited value has no specificity at all. Even the weakest rule that directly targets the element beats it:

#main { color: blue; }      /* (1, 0, 0), but only for #main itself */
p     { color: gray; }      /* (0, 0, 1), targets the p directly */
<div id="main">
  <p>I am gray, not blue</p>
</div>

Beginners often think "the ID is stronger, so the paragraph should be blue". But #main does not select the paragraph; it only selects the div. The paragraph would inherit blue only if no rule set its colour.


Controlling Inheritance: The CSS-wide Keywords

Every property accepts five special keywords that let you control the cascade and inheritance directly:

KeywordMeaning
inheritTake the parent's computed value, even for a non-inherited property.
initialUse the property's initial value from the specification (for color that is canvastext, normally black).
unsetAct like inherit if the property is inherited, otherwise like initial.
revertRoll back to the value the previous origin would give, usually the browser's default style.
revert-layerRoll back to the value from the previous cascade layer.
.child-inherit { border: inherit; }   /* now gets 2px solid red from .parent */
.u1  { color: unset; }               /* color inherits → parent's colour */
.u2  { border: unset; }              /* border doesn't inherit → initial: none */
.ini { color: initial; }             /* black, ignoring the parent's colour */

section.special { display: inline; }
section.special { display: revert; } /* back to the browser default: block */

We verified each of these in Chrome. Note the difference between initial and revert for display: the initial value of display is inline for every element, so div { display: initial; } makes a div inline. revert brings back the browser's style sheet value, which for a div is block. This is a common trap.

The all property

all resets every property (except direction, unicode-bidi and custom properties) at once:

.widget { all: revert; }   /* throw away author styles, start from browser defaults */

A practical example: form controls

Buttons, inputs and selects do not inherit the page font by default, because the browser's own style sheet sets a font on them. In Chrome, with a parent at font-size: 20px, a plain <button> still had a computed font size of 13.3333px. The usual fix found in almost every modern CSS reset:

button, input, select, textarea {
  font: inherit;
}

After this, the button computed to 20px, matching its parent.


From Declarations to Pixels: Value Stages

Interviewers sometimes ask about the "computed value". The browser processes each property in stages:

declared values   all declarations that match the element
      ↓  cascade picks a winner
cascaded value    the winning declaration (or nothing)
      ↓  defaulting: inherit / initial if nothing won
specified value   a value for every property
      ↓  resolve relative things: em → px, keywords, var()
computed value    this is what children inherit
      ↓  layout: percentages of widths, auto sizes
used value        final value used for drawing

For example, font-size: 1.5em with a parent of 20px has the computed value 30px, and children inherit 30px, not "1.5em". You will see why this matters in the chapter CSS Units. getComputedStyle() in JavaScript actually returns the "resolved value", which is the used value for some properties such as width.


Debugging with DevTools

Right-click an element, choose Inspect, and look at the Styles panel. Chrome and Firefox list every matching rule, most important on top. Declarations that lost the cascade are shown crossed out. The Computed tab shows the final value of each property, and you can expand it to see which rule it came from. Whenever you ask "why isn't my CSS applying?", this is the first place to look.

Common reasons a rule is crossed out or missing:

  • A more specific rule wins (check specificity).

  • A later rule with equal specificity wins (check file order).

  • The selector doesn't actually match (typo in class name, wrong nesting).

  • The value is invalid, shown with a warning icon.


Writing CSS That Doesn't Fight Itself

  • Prefer classes for styling. IDs have very high specificity and are hard to override later.

  • Keep selectors short and flat. .card-title is easier to override than #main .content div.card h2.title.

  • Avoid !important except for deliberate utility classes.

  • Use :where() for low-priority defaults that should be easy to override.

  • Use @layer to order resets, frameworks and components in large projects.

  • Set inherited properties high up (on body or :root) and let inheritance do the work.


Common Mistakes

  • Thinking the last rule always wins. Source order matters only when specificity (and everything before it) is a tie.

  • Treating specificity as a decimal number. (0, 11, 0) does not beat (1, 0, 0).

  • Thinking class order in HTML matters. class="a b" and class="b a" behave identically.

  • Expecting an inherited value to beat a direct rule. Inherited values have no specificity; any matching rule beats them.

  • Counting the universal selector or combinators. They add nothing.

  • Forgetting :is()/:not() take the most specific argument, even one that didn't match.

  • Using initial when you mean revert, for example display: initial turning a div inline.

  • Expecting layered rules to beat unlayered ones. For normal declarations, unlayered styles win.


Interview / Exam Questions

1. Calculate the specificity of #sidebar ul li.active a:hover.

IDs: #sidebar = 1. Classes/pseudo-classes: .active, :hover = 2. Types: ul, li, a = 3. Specificity = (1, 2, 3).

2. Which wins: .nav .item .link or #menu a?

.nav .item .link is (0, 3, 0); #menu a is (1, 0, 1). Column A is compared first, 1 > 0, so #menu a wins regardless of the class count.

3. Two rules have the same specificity. How is the conflict resolved?

By order of appearance: the declaration that comes later in the combined style sheets (considering <link> and <style> order) wins. This assumes both have the same origin, importance and layer.

4. What is the specificity of :where(#a .b) p and of :not(.x, #y) p?

:where() contributes nothing, so the first is (0, 0, 1). :not() takes its most specific argument, #y, so the second is (1, 0, 1).

5. Why does a user's !important rule beat an author's !important rule?

For accessibility. Users with special needs (large fonts, high contrast) must be able to override a website's styles. So the origin order is reversed for important declarations: user-agent important > user important > author important.

6. What is the difference between inherit, initial, unset and revert?

inherit copies the parent's computed value; initial uses the spec's initial value; unset behaves as inherit for inherited properties and initial otherwise; revert goes back to the previous origin's value, typically the browser default.

7. A paragraph is inside <div id="main" style="color: red">, and the CSS has p { color: blue; }. What colour is the paragraph text?

Blue. The inline style applies to the div, not the paragraph. The paragraph could only inherit red if no rule matched it, but p matches it directly.


Summary

  • The cascade chooses one value when several declarations conflict. It checks, in order: origin and importance, inline (element-attached) styles, layers, specificity, scope proximity, and finally order of appearance.

  • Specificity is (IDs, classes/attributes/pseudo-classes, types/pseudo-elements), compared column by column from the left. * and combinators count zero.

  • :is(), :not(), :has() take their most specific argument; :where() is always zero.

  • !important jumps above normal declarations but reverses origin and layer order; use it sparingly.

  • For normal declarations, unlayered styles beat layered ones, and later layers beat earlier ones.

  • Inheritance fills in values for properties no rule sets: text properties inherit, box properties don't. Inherited values lose to any rule that targets the element.

  • inherit, initial, unset, revert and revert-layer let you control this explicitly.

In the next chapter, Colors, we start looking at the actual values you put into all these declarations.