Loading

T2 CSS · Lesson 1

Selectors and rules

What CSS is and where styles go; a rule taken apart; choosing elements by type, class, id, groups, chains, descendants and children; the cascade, specificity and order; and inheritance.

  • say what CSS is, and put styles inline, in a style element, or in a stylesheet file
  • read and write a rule: its selector, its declarations, their properties and values
  • pick elements by name, class and id, and by groups, chains and descendants
  • work out which rule wins when two disagree: importance, specificity and order
  • say which properties a child inherits from its parent, and which it does not
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-10-27)Play this lesson's games

The back cover

A school does not dress each child by hand every morning. It writes the uniform rules once, and every child who follows them looks the same. Changing next year's tie means changing one line of the rules. CSS does this for web pages.

These pages take a CSS rule apart, then show the ways to choose what it dresses: by type, by class, by id, by place. They show how the browser settles an argument between two rules, and which styles children take from their parents.

Every rule on these pages was checked in Chrome, and the colours shown are the ones the browser really used.

Before you start

The story: The Tailors' Hall

The Tailors' Hall is all colour: bolts of cloth, chalk lines, pins in every cushion. Meher Daruwalla, its guildmistress, walks round your Lamplighters' Fair notice twice. "It stands," she says. "Tobin builds well. But it is grey and plain, and nobody will stop to read it."

Across the hall, Corin is painting the city's notices one at a time. He has done eleven. Each one is a slightly different shade, and his brush is dripping on the twelfth.

Meher sighs. "There are four hundred notices on the towers," she says. "Show me how to dress every one of them the same way, with one sheet of instructions, without touching a single frame."

The HTML step built pages that stand: every heading, paragraph, list, table and form in its right place, with its right meaning. They all look much the same, though: black text on white, in one plain font. This step, CSS, decides how they look. It builds on these ideas; each has a tiny example.

What you already knowA tiny exampleWhere it comes back
Elements and their names.<h1>, <p>, <nav>.CSS picks elements by their names.
class is a shared name.<p class="note"> on several paragraphs.CSS dresses every element with a class in one go.
id names exactly one element.<p id="total">.CSS can pick that one element.
Elements nest inside each other.An a inside a nav inside a header.CSS can pick the links inside the nav and no others.
The head holds information about the page.<title>, <meta>, <link rel="icon">.It also holds the page's styles, or a link to them.
A data URI holds a file inside its address.An SVG drawing in an img's src, in lesson 3 of HTML.These examples load a stylesheet the same way, so nothing is fetched.
Semantic HTML: meaning, not looks.A nav draws exactly like a div.CSS supplies all the looks, so HTML can keep to meaning.
The browser has defaults.An h1 is big and bold even if you say nothing.Those defaults are a stylesheet of the browser's own.
Checks that ask the browser.getComputedStyle() in the HTML lessons' checks.Every block here asks the browser what it actually drew.

By the end of this lesson you will be able to:

  • say what CSS is, and put styles inline, in a style element, or in a stylesheet file;
  • read and write a rule: its selector, its declarations, their properties and values;
  • pick elements by name, class and id, and by groups, chains and descendants;
  • work out which rule wins when two disagree: importance, specificity and order;
  • say which properties a child inherits from its parent, and which it does not.

In one line

CSS dresses the HTML you already know, choosing elements by their names, classes, ids and places; you need the HTML step's classes, ids and nesting.

What CSS is, and where it goes

At a glance

A school writes its uniform rules once, and every child who follows them looks the same. CSS, Cascading Style Sheets, is that rule book for web pages. HTML says what each part of a page is; CSS says how it looks: its colour, its size, its font, its place.

Styles can go in three places. Inline, in one element's style attribute, they dress that element only. In a style element, they dress one page. In an external file joined with link rel stylesheet, they dress every page of the site, so one change restyles them all.

Take a guess: If a site has 400 pages, how many files should you change to give them all a new colour?

Think of a school uniform. The school does not dress each child by hand every morning. It writes the rules once: white shirt, navy trousers, a striped tie. Every child who follows the rules looks the same, and changing the tie for next year means changing one line of the rules.

CSS

Cascading Style Sheets: the language that says how HTML looks. HTML says what each part of a page is; CSS says how it should appear: its colour, its size, its font, its place on the screen.

Keeping the two apart is the whole point. One stylesheet can dress every page of a site, so changing the site's colour means changing one line, not four hundred pages. The word cascading is about what happens when rules disagree, which the cascade section explains.

Three places to put styles

1. Inline, in the element's own style attribute. It dresses that one element only.

<p style="color: maroon">Shop closed on Sunday.</p>
<p>Open 8 am to 9 pm.</p>

Checked in Chrome

  • the first paragraph is maroon
  • the second, with no style, stays black

The browser reports every colour as three numbers, for red, green and blue, so maroon reads rgb(128, 0, 0); lesson 2 explains them. Inline styles are handy for a quick test, and a poor way to dress a site: every element would carry its own copy.

2. Internal, in a <style> element in the page's head. It dresses the whole page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Asha Stores</title>
    <style>
      h1 { color: teal; }
      p { color: maroon; }
    </style>
  </head>
  <body>
    <h1>Asha Stores</h1>
    <p>Fresh vegetables every morning.</p>
    <p>Open 8 am to 9 pm.</p>
  </body>
</html>

Checked in Chrome

  • the heading is teal
  • and every paragraph is maroon, from one rule

One rule, p { color: maroon; }, dressed both paragraphs, and would dress a hundred. The next section takes such a rule apart.

3. External, in a separate file, usually called styles.css, which every page joins with a <link> element in its head. It dresses the whole site.

On a real site

<link rel="stylesheet" href="styles.css">

The rel="stylesheet" says what kind of file it is, and href says where, as a path like those of the HTML step. To run here with no file, the next block gives the stylesheet's text inside the address, as a data URI, just as the HTML lessons did with pictures.

<link rel="stylesheet" href="data:text/css,h1{color:teal} p{color:maroon}">
<h1>Asha Stores</h1>
<p>Fresh vegetables every morning.</p>

Checked in Chrome

  • the linked sheet dresses the heading
  • and the paragraph
  • the page has one stylesheet, the linked file
WhereHowDressesUse it for
inlinestyle="..." on an elementthat elementa quick test; rarely anything else
internal<style> in the headone pagea single page, or trying things out
external<link rel="stylesheet" href="styles.css">every page that links itevery real site

One file for the whole site

Real sites use an external stylesheet. The browser also saves the file after the first page, so every later page opens faster.

Worked example 1

A coaching class's site has 30 pages, and the owner wants every heading in navy. Where should the style go, and what changes when the colour changes next year?

What we have: 30 pages, one look for all their headings

What we need: the right place for the style, and the cost of changing it

The plan: count how many places each choice would need to change

  1. Inline: a style attribute on every heading of every page, perhaps 200 places to change.
  2. Internal: a style element in each of the 30 pages, 30 places.
  3. External: one rule in styles.css, linked from every page, 1 place.
<link rel="stylesheet" href="data:text/css,h1{color:navy} h2{color:navy}">
<h1>Bright Minds Classes</h1>
<h2>Results</h2>

Checked in Chrome

  • one sheet makes both headings navy

An external stylesheet: next year's change is one line in one file.

Check: the count of places to change goes from about 200 to 30 to 1.

When you are stuck: where styles go

For anything more than a quick test, use an external stylesheet joined with link.

If a style does nothing, check that the link's href points at the real file, exactly as in the paths of the HTML step.

rel="stylesheet" must be there; without it the browser does not treat the file as styles.

Your turn

What does CSS stand for?Tap to reveal
  1. The C is about rules that disagree.

Cascading Style Sheets.

Which element joins a page to an external stylesheet?Tap to reveal
  1. It goes in the head, with rel and href.

<link rel="stylesheet" href="styles.css">.

Why do real sites put their styles in an external file?Tap to reveal
  1. Count the places a change would need.

Because one file dresses every page, so a change is made once.

Did you know?

CSS began at CERN in 1994

The saga of CSS starts in 1994, as its two creators put it. Håkon Wium Lie, then working at CERN, the cradle of the web, published a proposal called Cascading HTML style sheets on 10 October 1994. CSS level 1, by Lie and Bert Bos, became a W3C Recommendation on 17 December 1996.

Why it fits here: The style element and the stylesheet file of this topic are what that proposal set out to give the web.

Sources: Håkon Wium Lie and Bert Bos: The CSS saga (W3C); Håkon Wium Lie: Cascading HTML style sheets, a proposal (W3C); W3C: Cascading Style Sheets, level 1

One page, many looks

In May 2003 Dave Shea launched the CSS Zen Garden, a demonstration of what can be accomplished through CSS-based design. Every design it shows dresses the very same HTML page. In the site's own words, the HTML remains the same, and the only thing that changes is the external CSS file.

Why it fits here: The external stylesheet of this topic is the Zen Garden's whole trick: keep the HTML, change the file, change the look.

Sources: CSS Zen Garden: The Beauty of CSS Design; Wikipedia: CSS Zen Garden

In one line

CSS says how HTML looks; styles go inline (one element), in a style element (one page) or, for real sites, in an external file joined with link rel="stylesheet" (every page).

A rule, taken apart

At a glance

A tailor's order slip says two things: which garments, and what to do to them. A CSS rule has the same shape. The selector picks the elements; the block in curly brackets holds declarations, each a property, a colon, a value and a semicolon.

Read a rule aloud as a sentence: every h1, colour teal, font size 40 pixels. Comments go between slash star and star slash. Elements with no rules of yours still have styles, from the browser's own stylesheet, and the browser skips any declaration it cannot read.

Take a guess: If one property in a rule is misspelt, does the whole page break?

A tailor's order slip says two things: which garments, and what to do to them. "All school shirts: white, size 32, two pockets." A CSS rule has exactly that shape.

One rule

h1 {
  color: teal;
  font-size: 40px;
}
PartHereWhat it does
selectorh1picks which elements the rule dresses: every h1
declaration block{ ... }the curly brackets, holding what to do
declarationcolor: teal;one instruction: a property, a colon, a value, a semicolon
propertycolorwhat to change
valuetealwhat to change it to

Read the rule aloud as a sentence: "every h1: colour teal, font size 40 pixels". The whole thing, selector and block together, is called a rule, or a rule set. CSS is written in American spelling, so the property is color, never colour.

<style>
  h1 {
    color: teal;
    font-size: 40px;
  }
</style>
<h1>Asha Stores</h1>

Checked in Chrome

  • colour: teal
  • font size: 40 pixels

Each declaration ends with a semicolon, which separates it from the next. The last one may leave it out, but writing it always saves a slip when you add another line below. Spaces and new lines inside a rule are free: write one declaration per line, indented, so the rule reads like a list.

Comments

A comment in CSS starts with /* and ends with */. The browser skips it. Use comments to say why a rule is there.

<style>
  /* the guild's red, from the printed price list */
  h1 { color: maroon; }
</style>
<h1>Diwali offers</h1>

Checked in Chrome

  • the comment is skipped; the rule applies

The browser's own stylesheet

A page with no CSS at all still has styles: headings are big and bold, links are blue and underlined, the page has a small margin. These come from the user agent stylesheet, the browser's own built-in CSS. (A user agent is the program acting for the user: the browser.)

<h1>Asha Stores</h1>
<p>Fresh today.</p>
<a href="/offers">Offers</a>

Checked in Chrome

  • an h1 is 32 pixels and bold, with no CSS of yours
  • a link is blue
  • and the page has an 8 pixel margin

Your rules are laid on top of the browser's. Where you say nothing, its defaults stay; where you say something, yours win. That is why, in the cascade section, "which rule wins" matters so much.

When a rule is broken

CSS, like HTML, never shows an error on the page. The browser skips what it cannot understand and carries on with the rest. A misspelt property or a value it does not know is skipped on its own.

<style>
  p {
    colour: maroon;
    font-size: 20px;
  }
</style>
<p>Open 8 am to 9 pm.</p>

Checked in Chrome

  • colour (British spelling) is not a property, so it is skipped: the text stays black
  • but the next declaration still applies

A missing semicolon does more damage: the browser reads the two declarations as one long, wrong one, and skips both. A missing closing bracket changes every rule after it: the browser reads them as written inside the unclosed rule, so they choose only elements inside its elements. The mistakes section shows both.

Worked example 2

Write one rule that makes every paragraph maroon and 18 pixels tall, then read it aloud.

What we have: the elements (every paragraph) and the two changes

What we need: a rule with a selector and two declarations

The plan: the selector p; a block with two declarations, each a property, a colon, a value and a semicolon

<style>
  p {
    color: maroon;
    font-size: 18px;
  }
</style>
<p>Fresh today.</p>
<p>Open till 9.</p>

Checked in Chrome

  • both paragraphs: maroon, 18 pixels
  • Aloud: "every p: colour maroon, font size 18 pixels".
  • p { color: maroon; font-size: 18px; }

    Check: the check reads both paragraphs' computed styles and finds both changes on each.

    When you are stuck: rules

    Read the rule aloud: which elements, then each property and its value. If you cannot, a piece is missing.

    Every declaration: property, colon, value, semicolon.

    A style that does nothing is often a spelling slip: color, not colour; the browser skips what it does not know.

    Your turn

    In p { color: navy; }, which part is the property and which the value?Tap to reveal
    1. What to change, and what to change it to.

    Property color, value navy.

    How do you write a comment in CSS?Tap to reveal
    1. It starts with a slash and a star.

    /* like this */.

    Where do an h1's size and boldness come from when you write no CSS?Tap to reveal
    1. The browser has its own stylesheet.

    The user agent stylesheet, the browser's own.

    Did you know?

    Built to skip what it cannot read

    CSS was built to survive its own future. The CSS 2.1 standard says browsers must ignore a declaration with an unknown property, so that new properties can be added later. Its own example is h1 { color: red; rotation: 70minutes }, which a browser treats as h1 { color: red }.

    Why it fits here: This is why the browser of this topic skips a declaration it cannot read and keeps the rest of the rule.

    Source: W3C: CSS 2.1, rules for handling parsing errors

    The 8 pixels around every page

    A page with no CSS at all still has a small gap at its edges. The HTML standard lists the styles a browser is expected to use by itself, its user-agent style sheet. For the body, it expects a default margin of 8px, which is why plain text never quite touches the edge of the window.

    Why it fits here: The browser's own stylesheet in this topic is where that 8px margin lives.

    Source: HTML Standard (WHATWG): rendering

    In one line

    A rule is a selector and a block of declarations, each property: value; with a semicolon, and comments go in /* */. The browser's own stylesheet supplies the defaults, and the browser skips what it cannot read.

    Selectors: choosing what to dress

    At a glance

    A school notice can be for everyone, for a group such as the cricket team, or for one person by roll number. Selectors choose elements the same ways: p for every paragraph, .note for every element with that class, and #total for the one element with that id.

    They combine, too. A comma groups selectors that share a rule. Written with no space, they must all fit one element. A space means inside, at any depth; a greater-than sign means directly inside; and a star means every element.

    Take a guess: How would you choose only the paragraphs that sit inside a card?

    A school notice can be meant for everyone ("all students"), for a group ("the cricket team"), or for one person ("roll number 1042"). It can also be more exact: "the cricket team members in Class 10". Selectors choose elements in all the same ways.

    By name, by group, by one

    SelectorWrittenChoosesLike a notice for
    typepevery p elementall students
    class.noteevery element with class="note"the cricket team
    id#totalthe one element with id="total"roll number 1042
    <style>
      p { color: black; }
      .offer { color: maroon; }
      #today { color: teal; }
    </style>
    <p>Rice, 5 kg</p>
    <p class="offer">Dal, 10% off</p>
    <p class="offer">Sugar, 10% off</p>
    <p id="today">Today only: free delivery</p>

    Checked in Chrome

    • the plain paragraph: black, from the type selector
    • both offers: maroon, from the class selector
    • the one with the id: teal

    Read the marks aloud. The dot, ., means "class": .offer is "class offer". The hash, #, means "id": #today is "id today". In the HTML, the class and the id are written without them: class="offer", id="today".

    A memory aid

    Dot for a class, hash for an id. A class is a group, so it gets the small, common mark; an id is one of a kind.

    Prefer classes for styling. An id can be used only once on a page, so a style written for an id cannot be reused. Keep ids for what must be unique: links to a part of the page, labels and their boxes.

    Several classes on one element

    The class attribute can hold several names, separated by spaces. The element then belongs to each group, and takes each group's styles.

    <style>
      .sale { color: maroon; }
      .big { font-size: 24px; }
    </style>
    <p class="sale big">Diwali sale: 20% off</p>

    Checked in Chrome

    • maroon, from .sale
    • and 24 pixels, from .big
    • one element, two classes

    More exact selectors

    SelectorWrittenChoosesRead it as
    grouph1, h2every h1 and every h2"h1 and h2"
    chainedp.notep elements that also have class note"a p that is a note"
    descendantnav aa elements anywhere inside a nav"links inside the nav"
    childul > lili elements directly inside a ul"li children of a ul"
    universal*every element"everything"
    <style>
      h1, h2 { color: navy; }
      p.note { color: teal; }
      nav a { color: orange; }
    </style>
    <h1>Asha Stores</h1>
    <h2>Offers</h2>
    <p class="note">Prices include GST.</p>
    <div class="note">Not a p, so not teal.</div>
    <nav><a href="/">Home</a></nav>
    <a href="/help">Help, outside the nav</a>

    Checked in Chrome

    • the group: both headings navy
    • the chain: only the p with class note is teal
    • the descendant: only the link inside the nav is orange

    Look at the two that look alike. p.note, with no space, is one element that is both a p and a note. p .note, with a space, would be a note somewhere inside a p. One space changes the meaning.

    Descendant or child?

    A descendant selector reaches any depth: grandchildren too. The child selector, with >, reaches only one level down. To see the difference, the next block uses a background colour, since a background does not pass down to inner elements by itself.

    <style>
      ul > li { background-color: yellow; }
    </style>
    <ul>
      <li>Vegetables
        <ol>
          <li>Onion</li>
        </ol>
      </li>
    </ul>

    Checked in Chrome

    • the li directly inside the ul is yellow
    • the li inside the inner ol is not: it is not a child of the ul

    Worked example 3

    A shop's page has prices in many places, but only the prices inside product cards, written as <div class="card">, should be maroon. Each price is a <span class="price">. Write the selector.

    What we have: prices inside cards, and prices elsewhere

    What we need: a selector that reaches only the card prices

    The plan: a class for the card, a space for "inside", a class for the price

    <style>
      .card .price { color: maroon; }
    </style>
    <div class="card">Toor dal <span class="price">₹180</span></div>
    <p>Delivery: <span class="price">₹40</span></p>

    Checked in Chrome

    • the card's price is maroon
    • the delivery price, outside a card, is not
  • Read it as: "a price inside a card". The space is the word inside.
  • .card .price, with a space between.

    Check: the check finds the card's price maroon and the other price untouched.

    A path that fails: Writing .card.price, with no space. That chooses one element that is both a card and a price, and there is none, so nothing changes.

    When you are stuck: selectors

    Say in words which elements you mean, then translate: a name, a dot and a class, a hash and an id.

    A space means inside; no space means the same element; a comma means and.

    Check the HTML: the class must be spelt the same, and written there without the dot.

    Your turn

    Which selector chooses every element with class="price"?Tap to reveal
    1. A dot for a class.

    .price.

    What does nav a choose?Tap to reveal
    1. The space means inside.

    Every a inside a nav, at any depth.

    What is the difference between p.note and p .note?Tap to reveal
    1. Look at the space.

    p.note is a p that is a note; p .note is a note inside a p.

    Did you know?

    The same selectors in JavaScript

    The selectors of CSS also work in JavaScript. The W3C's Selectors API, a Recommendation from 21 February 2013, defines methods such as querySelectorAll, which find elements with a selector. Its own example replaces a nested loop over a table's rows with one call, and says the script becomes much more concise.

    Why it fits here: Every selector of this topic, from .offer to a child chosen with a greater-than sign, works the same way inside JavaScript.

    Source: W3C: Selectors API Level 1

    Name a class for what it is

    The HTML standard says a class attribute holds a set of space-separated tokens, so one element can belong to several classes at once. It puts no extra limits on the names, but it encourages names that describe the nature of the content, not the look you want. So .offer is a better name than .red: when the offers turn green, the name still fits.

    Why it fits here: The class selectors of this topic choose by those names, so a name that says what a thing is keeps working when its look changes.

    Source: HTML Standard (WHATWG): the class attribute

    In one line

    Selectors choose by type (p), class (.note) or id (#total); a comma groups them, no space chains them on one element, a space means inside, > means directly inside, and * means everything.

    The cascade: which rule wins

    At a glance

    At a school, the rule says black shoes, but on sports day the sports teacher says white. Both apply to the same feet, and the more particular rule wins. When CSS rules disagree, the cascade picks the winner, and it is the C of CSS.

    It asks three questions in order. Is one declaration marked !important? Is one more specific: an id beats any number of classes, and a class beats any number of types? If they are still equal, the rule that comes later wins. An inline style beats every selector without !important.

    Take a guess: Two rules give the same paragraph two colours: which one does the browser use?

    At a school, the headmaster's rule says "black shoes". The sports teacher's rule says "white shoes on sports day". On sports day, both rules apply to the same feet, and only one can win. Everyone knows the more particular rule wins: sports day is more exact than every day. CSS settles its arguments the same way.

    The cascade

    The browser's way of choosing a winner when several rules set the same property on the same element. It is the C of CSS. It asks three questions, in order: which rule is marked important, which is the most specific, and which comes last.

    Specificity: the more exact rule wins

    <style>
      p { color: maroon; }
      .note { color: teal; }
      #tip { color: navy; }
    </style>
    <p class="note" id="tip">Order by 10 am for lunch.</p>
    <p class="note">Prices include GST.</p>
    <p>Open till 9.</p>

    Checked in Chrome

    • the first paragraph matches all three rules; the id wins: navy
    • the second matches the type and the class; the class wins: teal
    • the third matches only the type: maroon

    The order of the rules in the sheet did not matter here: the id would win even if it came first. A selector's specificity is how exact it is, counted in three columns: ids, then classes, then types. Compare the columns from the left, like comparing marks subject by subject in a fixed order.

    SelectoridsclassestypesWritten as
    p0010, 0, 1
    nav a0020, 0, 2
    .note0100, 1, 0
    p.note0110, 1, 1
    .menu a0110, 1, 1
    #tip1001, 0, 0

    A single id, 1, 0, 0, beats any number of classes, since the ids column is compared first. A single class, 0, 1, 0, beats any number of types. So .note beats body div p, even though the second is longer.

    A memory aid

    Id, class, type: a hundred, ten, one. Think of an id as worth a hundred, a class ten and a type one. It is only a picture, because ten classes never add up to beat one id, but it gets the order right.

    Order: the later rule wins a tie

    When two rules are equally specific, the one that comes later wins. So a later stylesheet beats an earlier one, and a later rule in the same sheet beats an earlier one.

    <style>
      p { color: maroon; }
      p { color: teal; }
    </style>
    <p>Fresh today.</p>

    Checked in Chrome

    • two equal rules: the later one wins

    Inline styles and !important

    An inline style attribute beats every selector, because it is written on the element itself. And a declaration marked !important beats everything without it, inline styles included.

    <style>
      p { color: teal !important; }
    </style>
    <p style="color: maroon">Shop closed on Sunday.</p>

    Checked in Chrome

    • the !important rule beats even the inline style

    Reaching for !important

    !important feels like a quick fix when a style will not apply. It works once, and then the next fix needs another !important to beat the first, until the sheet is a shouting match. Find out why your rule loses, with the specificity columns, and make the selector exact enough instead. Keep !important for rare cases, such as a style that must win over code you cannot change.

    The cascade asks, in orderThe winner
    1. Is one declaration marked !important?the important one
    2. Is one written inline, on the element?the inline one
    3. Which selector is more specific (ids, then classes, then types)?the more specific one
    4. Still equal?the one that comes later

    Worked example 4

    A shop's sheet has nav a { color: navy; } and, later, .menu-link { color: orange; }. A link is written <nav><a class="menu-link" href="/">Home</a></nav>. Which colour does it get, and why?

    What we have: two rules on one link, the class rule later

    What we need: the winner, by the cascade's questions

    The plan: neither is important or inline, so compare specificity; if equal, order decides

    1. nav a: no ids, no classes, two types: 0, 0, 2.
    2. .menu-link: no ids, one class, no types: 0, 1, 0.
    3. Compare from the left: ids 0 and 0, a tie; classes 0 and 1, so .menu-link is more specific.
    <style>
      nav a { color: navy; }
      .menu-link { color: orange; }
    </style>
    <nav><a class="menu-link" href="/">Home</a></nav>

    Checked in Chrome

    • the class wins: orange

    Orange: 0, 1, 0 beats 0, 0, 2, whatever the order.

    Check: the browser drew it orange, as the columns said.

    Another way: Swap the two rules' order and run it again in your head: the answer stays orange, because order only settles ties.

    Worked example 5

    A developer writes p { color: maroon; } in the site's sheet, but one paragraph stays teal. In DevTools they find .intro p { color: teal; } in another sheet. How can they make that paragraph maroon without !important?

    What we have: a rule that loses to a more specific one

    What we need: a selector at least as specific, placed later, or more specific

    The plan: count .intro p, then write a selector that beats it

    1. .intro p is 0, 1, 1. The plain p, 0, 0, 1, loses.
    2. A selector with the same 0, 1, 1, placed later, wins the tie: .intro p again in the site's own sheet, loaded after the other.
    3. Or a more specific one, such as giving the paragraph a class: .intro p.lead, 0, 2, 1.

    A selector of equal specificity placed later, or a more specific one, such as .intro p.lead.

    Check: each choice wins by the cascade's own questions, so no !important is needed.

    A path that fails: Adding !important to the plain p rule. It wins today, but the next person who needs one paragraph teal must add !important too, and the sheet slides into a shouting match.

    When you are stuck: the cascade

    Find every rule that sets the property on the element: DevTools lists them, with the losers struck through.

    Ask the four questions in order: important, inline, specificity, order.

    Count specificity in three columns, ids, classes, types, and compare from the left.

    Your turn

    Which is more specific: #price or .card .price?Tap to reveal
    1. Compare the ids column first.

    #price: 1, 0, 0 beats 0, 2, 0.

    Two rules have the same specificity. Which wins?Tap to reveal
    1. The fourth question.

    The one that comes later.

    Why is !important a poor everyday fix?Tap to reveal
    1. What does the next fix need?

    Because each !important needs another to beat it, and the sheet becomes a shouting match.

    Did you know?

    The reader can overrule the page

    In CSS, the reader can win. Both the page's author and the reader may mark declarations !important, and the reader's important rules override the author's. The CSS standard says this improves accessibility, giving users with special requirements, such as large fonts or certain colour combinations, control. CSS1 had it the other way round, and CSS2 changed it.

    Why it fits here: The !important of this topic sits at the top of the cascade, and a reader's own !important sits above the page's.

    Sources: W3C: CSS 2.1, the cascade; W3C: CSS 2, the cascade

    Specificity is counted in three numbers

    The selectors standard counts a selector's specificity as three numbers: its ids, then its classes and the like, then its types. Two selectors are compared on the first number, and the next number counts only on a tie. So one id outweighs any number of classes, and one class outweighs any number of types.

    Why it fits here: This is the counting behind this topic's rule that an id beats a class and a class beats a type.

    Source: W3C: Selectors Level 4, calculating a selector's specificity

    In one line

    When rules disagree, the cascade picks the winner: an !important declaration, then an inline style, then the more specific selector (ids, then classes, then types), then the later rule.

    Inheritance: what children take from parents

    At a glance

    Children take their family's language and surname without being taught each one, but not the house's front door. In CSS, some properties set on an element pass down to the elements inside it: mostly text properties, such as colour and fonts.

    Box properties, such as borders, backgrounds and margins, do not pass down; picture a border drawn again round every word inside a card. Any rule that chooses the child itself beats what the child would inherit, however weak its selector. So a font set once on the body reaches every paragraph that sets none of its own.

    Take a guess: If a card has a border, should every paragraph inside it get a border too?

    Children often take their family's language and surname without being taught each one. But a child does not inherit the house's front door or the paint on its walls. CSS works the same way: some properties of an element pass down to the elements inside it, and some do not.

    Inheritance

    Some properties, set on an element, are taken by the elements inside it unless they set their own. These are inherited properties: mostly about text, such as colour and fonts. Others, mostly about boxes, such as borders and backgrounds, are not inherited.

    <style>
      .card {
        color: purple;
        font-family: serif;
        border: 2px solid black;
      }
    </style>
    <div class="card">
      <p>Toor dal, 1 kg: ₹180</p>
    </div>

    Checked in Chrome

    • the p inside the card takes its purple
    • and its font
    • but not its border: the p has none of its own

    Picture the page if borders did pass down: the card's border would be drawn round the card, again round the paragraph, again round every word in bold, a nest of boxes. That is why box properties stay with the element they are set on.

    Usually inherited (about text)Not inherited (about the box)
    color, font-family, font-size, font-weightborder, background-color
    line-height, text-align, letter-spacingmargin, padding
    list-style-type, visibilitywidth, height, display

    One rule on body dresses the page

    Because text properties inherit, a single rule such as body { font-family: sans-serif; color: navy; } sets the font and colour of the whole page. Every element takes them, unless a more particular rule says otherwise.

    A set value beats an inherited one

    Inheritance is the weakest way to get a value. If any rule at all chooses the child itself, the child keeps that, whatever its parent says.

    <style>
      body { color: navy; }
      .price { color: maroon; }
    </style>
    <p>Rice, 5 kg: <span class="price">₹650</span></p>

    Checked in Chrome

    • the paragraph takes navy from the body
    • but the price has its own rule, so it is maroon

    Asking to inherit: inherit

    The value inherit makes an element take its parent's value for any property, even one that is not usually inherited.

    <style>
      .card { border: 2px solid black; }
      .card p { border: inherit; }
    </style>
    <div class="card"><p>Inside the card</p></div>

    Checked in Chrome

    • with border: inherit, the p takes the card's border too

    Worked example 6

    A whole page turns purple, though only the shop's banner was meant to be. The sheet has body { color: purple; }, written by mistake for the banner. Why did every paragraph change, and what is the fix?

    What we have: a colour set on body, and every element purple

    What we need: the reason, and a rule that colours only the banner

    The plan: remember which properties inherit, and which element the rule chose

    1. color is an inherited property.
    2. The rule chose body, which holds every element on the page, so every element inherited purple.
    3. The fix is to choose the banner itself.
    <style>
      .banner { color: purple; }
    </style>
    <header class="banner">Diwali sale</header>
    <p>Open till 9.</p>

    Checked in Chrome

    • the banner is purple
    • and the paragraph stays black

    colour inherits from body to everything; choose .banner instead.

    Check: after the fix, only the banner and the elements inside it are purple.

    When you are stuck: inheritance

    Ask: is this property about text (usually inherited) or about the box (usually not)?

    If an element has a colour you never gave it, look at its parents: it probably inherited it.

    DevTools' Styles pane lists the inherited rules too, under "Inherited from".

    Your turn

    Does background-color pass from a div to the paragraph inside it?Tap to reveal
    1. Is it about text or about the box?

    No: it is a box property.

    A body rule sets colour navy, and a rule on .price sets maroon. What colour is a price inside a paragraph?Tap to reveal
    1. A set value beats an inherited one.

    Maroon: its own rule beats the inherited navy.

    Which value makes an element take its parent's value for any property?Tap to reveal
    1. One word.

    inherit.

    Did you know?

    Every property says yes or no

    Every CSS property is defined in a standard with a small table, and one line of it says Inherited: yes or no. The CSS Color standard says yes for color. The CSS Backgrounds standard says no for background-color, whose starting value is transparent, so a child's own background is see-through and shows its parent's.

    Why it fits here: The two lists of this topic, what passes down and what does not, come straight from those tables.

    Sources: W3C: CSS Color Module Level 4, the color property; W3C: CSS Backgrounds and Borders Module Level 3

    Borders do not inherit, but they borrow

    A border's colour is not inherited, yet a border given no colour still has one. In the CSS Backgrounds standard, the starting value of a border's colour is currentColor. The CSS Color standard defines currentcolor as the value of the color property on the same element, so the border takes the colour of its element's text.

    Why it fits here: This topic's border stays on its own element, but it still matches that element's text colour unless you give it one.

    Sources: W3C: CSS Backgrounds and Borders Module Level 3, border colours; W3C: CSS Color Module Level 4, the currentcolor keyword

    In one line

    Text properties such as colour and fonts pass down from parents to children; box properties such as borders, backgrounds and margins do not. Any rule that chooses the child beats what it would inherit.

    Where it is used

    Every site you have ever visited is dressed by rules like these.

    What you learnedWhere it is usedA real example
    an external stylesheetevery real sitea bank's 2,000 pages all link one styles.css, so its brand colour changes in one line
    type selectorsthe site's base looka rule on body sets the font of a whole news site
    class selectorsevery reusable pieceevery product card on a shopping site carries class="card"
    several classessmall, combinable stylesa button with class="btn btn-primary": one class for the shape, one for the colour
    descendant selectorsstyles that depend on placelinks inside the footer are grey; links inside an article are blue
    the cascade and specificityevery time two rules meeta site's own sheet, loaded after a library's, wins the ties
    inheritancefonts and colours for whole regionsa dark footer sets its colour once, and every line inside it takes it

    Mistakes and debugging

    CSS never shows an error. A broken rule is skipped, and the page looks as if you wrote nothing. Here are the slips that cause that silence.

    1. A missing semicolon

    <style>
      p { color: teal font-size: 20px; }
    </style>
    <p>Fresh today.</p>

    Checked in Chrome

    • (the slip: the two declarations run together into one bad one, and both are lost)

    The fix: color: teal; font-size: 20px;. Every declaration ends with a semicolon.

    2. A missing closing bracket

    <style>
      p { color: teal;
      span { color: maroon; }
    </style>
    <p>Fresh today.</p>
    <span>Offers</span>

    Checked in Chrome

    • (the slip: the browser reads one rule, with the span rule nested inside the p rule)
    • (so the p is teal, but the span outside every p stays black)

    Modern CSS lets one rule be written inside another, called nesting: a rule inside the p rule chooses only elements inside a p. With the bracket left open, the browser reads the span rule as nested, so it now means "spans inside a paragraph", and the span outside stays black. The fix: close every block: p { color: teal; }. When the rules after some point all stop working, look for an unclosed bracket above them.

    3. The dot in the wrong place

    <style>
      note { color: teal; }
    </style>
    <p class="note">Prices include GST.</p>

    Checked in Chrome

    • (the slip: without its dot, note means an element called note, and there is none)

    The fix: .note in the CSS, and plain class="note" in the HTML. The dot belongs only in the selector.

    4. A class spelt differently

    Class names must match exactly, capitals included: .Price does not choose class="price". A page with no doctype, in the old quirks mode of the HTML step, ignores the capitals. That hides the slip until the doctype is added. The fix: small letters and hyphens for every class name, as for file names.

    5. A rule that loses

    The rule is right, but a more specific one, perhaps in another sheet, wins. The fix: count the specificity columns, and write a selector that wins honestly, not !important.

    6. Styling with ids

    #price1, #price2, #price3: one rule for each, since an id is used once. The fix: one class, .price, on all of them.

    The debugging corner: the Styles pane

    Right-click an element and choose Inspect. DevTools' Styles pane lists every rule that chooses it, most specific first. A declaration that lost is struck through; one the browser could not read has a warning sign beside it. The Computed tab shows the final value of each property, and which rule it came from. Between them, they explain every "my CSS does nothing".

    Quick card

    The lesson on one card.

    Every idea of the lesson

    <link rel="stylesheet" href="data:text/css,body{color:navy} .note{color:teal}">
    <style>
      /* a group, a chain, a descendant and an id */
      h1, h2 { color: maroon; }
      p.note { font-size: 18px; }
      nav a { color: orange; }
      #today { color: purple !important; }
    </style>
    <h1>Asha Stores</h1>
    <nav><a href="/">Home</a></nav>
    <p class="note">Prices include GST.</p>
    <p>Plain text inherits navy from the body.</p>
    <p id="today" style="color: black">Free delivery today</p>

    Checked in Chrome

    • the group: maroon heading
    • the class from the linked sheet, the chain from the style element
    • the descendant: the nav link
    • inheritance: the plain paragraph takes navy from body
    • !important beats even the inline style
    IdeaIn one line
    CSShow HTML looks; external file, linked with <link rel="stylesheet" href="styles.css">
    a ruleselector { property: value; }; comments in /* */
    type, class, idp, .note (dot), #total (hash); prefer classes
    group, chainh1, h2 (and); p.note (both, no space)
    descendant, childnav a (inside, any depth); ul > li (directly inside)
    the cascade!important, then inline, then specificity (ids, classes, types), then later wins
    inheritancetext properties pass down; box properties do not; inherit asks for it
    the browser's defaultsthe user agent stylesheet, under every rule of yours

    The story: One sheet for four hundred

    You write one sheet of rules. Each rule names the pieces it dresses and says how: every main heading in the guild's deep red, every notice of the fair with its own class, the date picked out by its single id. When two rules argue, you know which wins, and why.

    Meher hangs your sheet on the hall's master tower. Across the city, four hundred notices change at once, every one alike.

    Corin looks at his eleven painted panels. "I could have stopped at one," he says. Meher hands him a sheet of his own.

    Reagents gathered: selector, declaration, class, specificity, cascade, inheritance.

    Sources

    • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
    • HTML Living Standard (WHATWG) (CC BY 4.0: "Copyright WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License" (its acknowledgements page, read 2026-10-26); reused with credit)