Log inSign up free
Mastering Modern CSS: From Zero to Pro
  1. Getting started

    1. CSS Lesson 1: What Is CSS?
    2. CSS Lesson 2: Selectors and Rules
    3. CSS Lesson 3: How CSS Works: The Cascade
    4. CSS Lesson 4: Colour and Backgrounds
    5. CSS Lesson 5: Typography and Text
    6. CSS Lesson 6: The Box Model
    7. CSS Lesson 7: Units and Sizing
    8. CSS Lesson 8: Display and Positioning
    9. CSS Lesson 9: Flexbox
    10. CSS Lesson 10: Grid
    11. CSS Lesson 11: Responsive Design
    12. CSS Lesson 12: Final Project
Mastering Modern CSS: From Zero to Pro

Getting started · Lesson 3 of 12 · 12 min read · By Jack

CSS Lesson 3: How CSS Works: The Cascade

In Lesson 2 you saw that a <p class="note"> turned green even though a p rule said black. Why? This is the heart of CSS, and the cause of most beginner frustration.

Part 1: The big question (3 min)

In Lesson 2 you saw that a <p class="note"> turned green even though a p rule said black. Why? This is the heart of CSS, and the cause of most beginner frustration.

<p class="note" id="lead">Hello</p>
p      { color: black; }  
.note  { color: green; }  
#lead  { color: blue; }

All three rules target the same paragraph and set the same property, so there's a conflict. The browser has a system for settling it, called the cascade.

Where do styles come from? Three places:

  1. The browser's default stylesheet. This is why headings are big and bold before you write any CSS.
  2. Your stylesheet. The CSS you write.
  3. The user's settings. Such as a larger default font size.

Your CSS beats the browser defaults. Your job is to understand how your own rules compete with each other.


Part 2: The three tie-breakers (4 min)

When rules conflict on the same property, the browser checks these in order. It stops at the first one that picks a winner.

StepQuestionWinner
1. ImportanceIs any declaration marked !important?That one
2. SpecificityWhich selector is more specific?The more specific
3. Source orderWhich rule comes last?The later one

Most of the time, step 2 or 3 settles it.

Source order (the simplest)

When two rules are equally specific, the last one wins.

p { color: red; }  
p { color: blue; }

The paragraph is blue. The same applies across files: if base.css is linked first and theme.css second, theme.css wins ties.

<link rel="stylesheet" href="base.css">  
<link rel="stylesheet" href="theme.css">

Note that rules don't replace each other entirely, only the properties that conflict.

p { color: red; font-size: 20px; }  
p { color: blue; }

The paragraph is blue and 20px. Only color conflicted.

Quick check A. What colour is the heading?

h1 { color: green; }  
h1 { color: orange; }

Quick check B. What colour and size is this paragraph?

p { color: purple; font-size: 24px; }  
p { color: teal; }

Part 3: Specificity (7 min)

Specificity measures how precisely a selector targets an element. A precise selector beats a vague one, regardless of order.

.note { color: green; }   /* more specific */  
p     { color: black; }   /* less specific, comes later but still loses */

A <p class="note"> is green even though the p rule comes last.

The scoring system

Count each part of a selector in four columns, written like 0,0,0,0:

ColumnWhat it countsExamples
1stInline stylesstyle="..."
2ndIDs#intro
3rdClasses, attributes, pseudo-classes.note, [type="text"], :hover
4thElementsp, h1, ::before

The universal selector * and combinators (space, >, +) add nothing.

Compare columns left to right. The first column with a different number decides, and bigger wins.

Worked examples

SelectorInlineIDsClassesElementsScore
p00010,0,0,1
.note00100,0,1,0
p.note00110,0,1,1
nav a:hover00120,0,1,2
#intro01000,1,0,0
#main .card p01110,1,1,1

Comparing two selectors

nav a        { color: black; }  /* 0,0,0,2 */  
.menu a      { color: green; }  /* 0,0,1,1 */

The second wins, because the class column holds 1 against 0.

A common trap. Columns don't carry over, so 11 elements never beat 1 class.

html body div section article p span { color: red; }  /* 0,0,0,7 */  
.highlight { color: green; }                          /* 0,0,1,0 */

.highlight wins. Nothing in the element column can outrank a single class.

Inline styles and IDs

  • An inline style (0,1,0,0 in the first column) beats every selector in a stylesheet.
  • IDs beat any number of classes.

That's why classes are the sweet spot for styling. They're specific enough to override element rules, but easy to override themselves when needed. IDs are so strong that they force you to use ever-stronger selectors later.

Pseudo-classes count as classes.

a        { color: blue; }    /* 0,0,0,1 */  
a:hover  { color: red; }     /* 0,0,1,1 */

On hover, the second rule wins as it's more specific. This works in either order.

Quick check C. Calculate the specificity score of each:

  • a) h2
  • b) .card .title
  • c) #sidebar a
  • d) ul li.active

Quick check D. Which colour wins?

#intro   { color: red; }  
.lead    { color: green; }  
p.lead.big { color: blue; }

for <p id="intro" class="lead big">.


Part 4: Inheritance (5 min)

Some properties flow down from parent to child. Set color on <body> and every element inside gets it, without any extra rules.

body {  
  font-family: Arial, sans-serif;  
  color: #374151;  
}

Paragraphs, headings, list items and links' text (apart from the browser's default link colour) all follow suit.

Which properties inherit? Mostly text-related ones.

Usually inheritedNot inherited
colormargin
font-familypadding
font-sizeborder
font-weightbackground
line-heightwidth, height
text-aligndisplay, position

The logic: you'd want a whole page to share a font, but you wouldn't want every child to get the parent's border or margin.

Inherited values are the weakest. Any rule that targets an element directly beats an inherited value, whatever its specificity.

body { color: green; }  
p    { color: black; }

Paragraphs are black. The p rule targets them directly, while the body colour is only inherited.

The inheritance keywords

Three special values give you control.

.box {  
  border: 2px solid red;  
}  
  
.box p {  
  border: inherit;       /* use the parent's border */  
}  
  
h2 {  
  color: initial;        /* the CSS default (usually black) */  
}  
  
.reset {  
  all: unset;            /* remove all styling from this element */  
}
KeywordEffect
inheritTake the parent's value
initialUse the CSS default for that property
unsetinherit if the property normally inherits, otherwise initial

You'll rarely need these, but inherit is useful for links:

a {  
  color: inherit;  /* links take the text colour of their parent */  
}

Quick check E. Look at this code. What colour is the <span> text, and why?

<div class="card"><p>Hello <span>world</span></p></div>
.card { color: crimson; }

Quick check F. If you set border: 1px solid black on a <div>, will the paragraphs inside also get borders? Why or why not?


Part 5: !important (2 min)

Adding !important to a declaration makes it win over normal specificity.

p {  
  color: red !important;  
}  
  
#intro {  
  color: blue;   /* loses, despite the ID */  
}

It sounds like a handy fix, but it causes problems:

  • The only way to beat it is another !important, so rules escalate.
  • Your CSS becomes unpredictable and hard to debug.
  • You can't tell why a style applies by reading the cascade.

Better fixes:

  1. Check for a typo, a missing brace or a wrong path first.
  2. Simplify the competing selector.
  3. Reorder the rules.
  4. Give your rule a class so it's a little more specific.

Reserve !important for rare cases, like a small utility class that must always win.

Quick check G. A rule isn't applying, and a teammate suggests adding !important. Name two things you'd try first.


Part 6: Debugging the cascade with DevTools (5 min)

DevTools shows exactly which rules apply and which lose.

  1. Right-click the element and choose Inspect.
  2. In the Styles panel, rules are listed from strongest at the top to weakest at the bottom.
  3. A declaration with a line through it lost, because something stronger overrode it (or it was invalid).
  4. The file name and line number appear on the right of each rule, so you know where to edit.
  5. Under Inherited from ... you can see which values came from parents.
  6. The Computed tab shows the final value for each property. Click the small arrow next to a value to jump to the rule that set it.

A debugging routine:

  1. Inspect the element.
  2. Find the property that isn't working.
  3. Is it struck through? If so, look at the rule above it. That's the winner.
  4. Compare the specificity of both selectors.
  5. Fix the selector or the order, not with !important.
  6. Check that the change works, then copy it into your CSS file.

If the property doesn't appear at all, your selector isn't matching. Re-check spelling, dots and hashes, as in Lesson 2.


Part 7: Writing CSS that cascades well (4 min)

Your habits can make the cascade easy or painful. Follow these guidelines:

DoAvoid
Style with classesStyling with IDs
Keep selectors short (one or two parts)body div .wrap ul li a
Put general rules first, specific ones laterRandom ordering
Set shared text styles once on body and let them inheritRepeating font-family everywhere
Fix conflicts by simplifyingAdding more and more specificity
Use DevTools to understand a problemGuessing, then using !important

A sensible stylesheet order is:

/* 1. Base: element defaults and inherited text styles */  
body { font-family: Arial, sans-serif; color: #374151; }  
a    { color: #1d4ed8; }  
  
/* 2. Components: classes */  
.card       { border: 1px solid #d1d5db; }  
.card-title { font-size: 1.25rem; }  
  
/* 3. Variations and states */  
.card.featured { border-color: #eab308; }  
.card:hover    { box-shadow: 0 2px 8px rgba(0,0,0,.15); }

Because the rules go from general to specific, nothing fights.


Common mistakes

MistakeFix
Expecting the later rule to win regardless of selectorCompare specificity first, then order
Thinking 10 elements beat 1 classColumns never carry over
Expecting margin or border to inheritThey don't, so set them on the element
Using #id for everythingUse classes
Reaching for !importantDebug and simplify instead
Editing in DevTools and forgetting to copy changesDevTools edits vanish on refresh
Forgetting inline styles beat stylesheet rulesRemove the inline style

Key takeaways

  • The cascade decides conflicts: importance, then specificity, then source order.
  • Specificity is scored in columns (inline, IDs, classes, elements), compared left to right.
  • Equal specificity means the last rule wins.
  • Text properties like color and font-family inherit, but box properties like margin and border don't.
  • Rules that target an element directly beat inherited values.
  • !important is a last resort. Simplify instead.
  • DevTools shows struck-through losers and the winning rule above them.

Exercises (15 min guided, plus extras)

1. Predict the winner (3 min). What colour is each paragraph?

<p class="a">One</p>  
<p class="a b">Two</p>  
<p id="x" class="a">Three</p>
p      { color: black; }  
.a     { color: green; }  
.b     { color: orange; }  
#x     { color: blue; }  
p.a    { color: red; }

2. Score the selectors (3 min). Write the specificity and rank the five from weakest to strongest:

  • a) li
  • b) ul li
  • c) ul .item
  • d) #menu li
  • e) .menu .item:hover

3. Inheritance quiz (2 min). For each property, write inherited or not inherited: color, padding, font-family, border, text-align, background-color.

4. Fix without !important (3 min). This heading should be green, but it's blue. Fix it using a better selector or order.

<h1 class="title">Welcome</h1>
.title { color: green; }  
h1.title { color: blue; }

(Imagine you want green, and you can edit either rule.)

5. Build it: a cascade experiment (7 min). Create cascade.html and cascade.css.

  1. Add a <div class="card"> with an <h2>, a <p> and a <span> inside the paragraph.
  2. Set color and font-family on body, and watch the card inherit them.
  3. Add border: 2px solid red to .card and notice it doesn't appear on the children.
  4. Write p, .card p and #special rules that all set the paragraph color. Predict the colour before refreshing.
  5. Swap their order in the CSS and observe what changes (and what doesn't).
  6. Inspect the paragraph in DevTools and find the struck-through rules.

6. Challenge (2 min). Pick five selectors from this lesson and work out each one's specificity score. Then check yourself in DevTools.


Lesson 3 checkpoint

  • I can explain the three tie-breakers.
  • I can score a selector's specificity.
  • I know why a class beats any number of elements.
  • I know which properties inherit and which don't.
  • I can explain why !important is a last resort.
  • I can find the winning rule in DevTools.


⬇️ ANSWER KEY (only scroll once you've tried the questions)

Quick check A: Orange. Equal specificity, so the later rule wins.

Quick check B: Teal, 24px. Only color conflicts, and font-size carries on from the first rule.

Quick check C:

  • a) 0,0,0,1
  • b) 0,0,2,0
  • c) 0,1,0,1
  • d) 0,0,1,2

Quick check D: Red. #intro has an ID (0,1,0,0), which beats p.lead.big (0,0,3,1) and .lead (0,0,1,0). One ID outranks any number of classes.

Quick check E: Crimson. color is inherited: the span inherits from the p, which inherits from .card.

Quick check F: No. border isn't an inherited property, so only the <div> gets a border.

Quick check G: Any two of: check for typos, missing semicolons or braces, a wrong file path; inspect the element in DevTools and compare specificity; simplify or reorder the selectors; give the rule a class.

Exercise 1:

  • One: red. p.a (0,0,1,1) beats .a (0,0,1,0) and p.
  • Two: red. It has classes a and b, but p.a (0,0,1,1) beats .b (0,0,1,0).
  • Three: blue. #x (0,1,0,0) beats everything else.

Exercise 2:

  • a) 0,0,0,1
  • b) 0,0,0,2
  • c) 0,0,1,1
  • d) 0,1,0,1
  • e) 0,0,3,0... see correction below.

Correction for e): .menu .item:hover has two classes and one pseudo-class, so its score is 0,0,3,0. Ranking weakest to strongest: a, b, c, e, d. 0,0,3,0 is weaker than 0,1,0,1 because the ID column is compared first.

Exercise 3: color inherited, padding not inherited, font-family inherited, border not inherited, text-align inherited, background-color not inherited.

Exercise 4: The h1.title rule (0,0,1,1) beats .title (0,0,1,0). Simplest fix: delete the h1.title rule, or change its colour to green. Better still, keep one .title rule so there's no competition.

Exercise 5: Check that the card inherits the body font and colour, that the border appears only on the card, and that #special wins over .card p, which wins over p. Reordering changes nothing, because their specificities differ. Only equal-specificity rules depend on order.

Exercise 6: Check against the Score column in the CSV.

Keep track of your learning

Create a free account to unlock them and track your progress.

  • Track your progress through every course
  • Take the quizzes and see your score
  • Download the worksheets and resources
  • Get a certificate when you finish

Related reading on our blog

Rather have it done for you?

We build websites for small businesses

Everything in this course is what we do every day for local businesses: fast, mobile-friendly sites that are built to be found on Google. See our web design services or our website packages.