Thuta Learning
CSS
BasicWeb DevelopmentBeginner

Selectors

CSSLesson 530 min

What you'll walk away with

  • Write type, class, ID and universal selectors and selector lists
  • Tell .a.b (one element with both classes) apart from .a .b (a descendant)
  • Calculate a selector's specificity as (ID, class, type)
  • Explain that source order decides ties and that !important only hides the real problem

Explain it simply

Explain it simply

A selector works like an address. "p" means "to every paragraph", ".note" means "to every element labelled with the note class", and "#intro" means "to the single element with id=intro". The more precise the address, the fewer elements it reaches.

When two addresses reach the same element with conflicting orders (one says blue, the other says red), the browser trusts the more precise address. That measure of precision is called specificity.

Problem → Why → Solution

The problem: the danger button will not turn red, so you add !important

A rule #sidebar .button already makes sidebar buttons blue. Now you want the "Delete account" button red, so you add a .button-danger class and write its rule at the very bottom of the stylesheet. The button stays blue. You expected the last rule to win, so you are confused, and adding !important makes it work.

A week later someone wants the disabled state grey, but their rule cannot beat !important either, so they add another !important.

buttons.css
#sidebar .button {          /* specificity (1,1,0) */
  background-color: #1d4ed8;
}
.button-danger {             /* (0,1,0): loses, even though it comes later */
  background-color: #b91c1c;
}
/* the "fix" that starts an arms race */
.button-danger { background-color: #b91c1c !important; }

Why does this happen?

Source order (the later rule wins) only applies when specificity is equal. #sidebar .button contains an ID, so it beats the single-class .button-danger wherever that rule is written. !important overrides this, but it only hides the real problem: an unnecessarily specific selector with an ID in it. The real fix is to drop the ID and use a single class such as .sidebar-button.

Core concept: selector types and specificity

SelectorWhat it selectsSpecificity
pEvery <p> element (type selector)(0,0,1)
.noteEvery element with class="note"(0,1,0)
#introThe one element with id="intro"(1,0,0)
*Every element (universal)(0,0,0)
article pEvery p inside an <article> (descendant)(0,0,2)

Selectors can be combined. Written together with no space, they mean "one element must match all of this": p.note is a paragraph with the note class, and .card.featured is an element with both classes. A space creates a descendant selector: .card .featured is a .featured element somewhere inside a .card. A comma makes a selector list: h1, h2 selects both h1 and h2 elements.

Specificity is counted in three columns: (number of IDs, number of classes, attributes and pseudo-classes, number of types and pseudo-elements). Compare from left to right; the first column that differs decides. So (1,0,0) beats (0,5,0): no number of classes outweighs one ID. The universal selector * and combinators such as a space or > add nothing.

Specificity is only one step of the cascade. The browser first looks at origin and importance (is there !important?), then at the order of cascade layers if you use them, then at specificity, and if that ties, the rule that comes later in the stylesheet wins. An inline style attribute outranks all selector rules. That is why the winning strategy is to keep specificity low and even: write most rules with a single class and avoid IDs for styling, so overriding a rule is as simple as writing another one after it.

You do not always have to count by hand: in the DevTools Styles pane, hovering over a selector shows its specificity, such as (1,0,1), in a tooltip in most browsers. Still, counting it yourself lets you predict whether a rule will win before you even write it.

Mental model: when two rules conflict
  1. Check for !important first
  2. Compare (ID, class, type) left to right
  3. Still tied: the later rule wins

The contest happens per property: a losing rule's other properties still apply.

General pattern: the basic selectors

selectors.css
element { }             /* every <element> */
.class-name { }         /* every element with class="class-name" */
#id-name { }            /* the one element with id="id-name" */
* { }                   /* every element */
element.class-name { }  /* one element matching both */
ancestor descendant { } /* descendant anywhere inside ancestor */
first, second { }       /* selector list: both */

In the HTML you write class="note" without a dot, and in the CSS you write .note with a dot. IDs work the same way: id="intro" in the HTML, #intro in the CSS.

Example: paragraphs touched by several rules

This page has four paragraphs, and each one is touched by a different set of rules. Before opening it, write down your prediction for each paragraph's colour, boldness and line height, then check against DevTools.

selectors.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Selectors</title>
  <style>
    p { color: #374151; }                     /* (0,0,1) */
    .note { color: #1d4ed8; }                 /* (0,1,0) */
    #intro { color: #b91c1c; }                /* (1,0,0) */
    p.note { font-weight: bold; }             /* (0,1,1) */
    h1, h2 { font-family: Georgia, serif; }   /* selector list */
    article p { line-height: 1.8; }           /* (0,0,2) descendant */
  </style>
</head>
<body>
  <article>
    <h1>Selectors</h1>
    <p id="intro" class="note">Intro paragraph</p>
    <p class="note">A note</p>
    <p>Plain paragraph</p>
  </article>
  <h2>Outside the article</h2>
  <p>Outside paragraph</p>
</body>
</html>

Code breakdown

  1. Three rules want the colour#intro { color: #b91c1c; } /* (1,0,0) */

    For the first paragraph, p (0,0,1), .note (0,1,0) and #intro (1,0,0) all try to set color. #intro has a 1 in the ID column, so it wins and the paragraph is red.

  2. Class beats type.note { color: #1d4ed8; } /* (0,1,0) */

    "A note" has no ID, so only p and .note compete. (0,1,0) is larger than (0,0,1) in the second column, so it is blue.

  3. Compound selectorp.note { font-weight: bold; } /* (0,1,1) */

    p.note, with no space, selects only paragraphs that have the note class, so the first two paragraphs are bold. No other rule sets font-weight, so nothing competes here; #intro winning the colour does not affect this bold.

  4. Descendant selectorarticle p { line-height: 1.8; } /* (0,0,2) descendant */

    The space means "inside", so only the three paragraphs within <article> get line-height 1.8. "Outside paragraph", after the article, keeps the browser's default line height.

  5. Selector listh1, h2 { font-family: Georgia, serif; } /* selector list */

    The comma selects both h1 and h2 in one rule instead of two. The h2 is outside the article, but this selector has no descendant condition, so it still matches.

You should see
"Intro paragraph": dark red (#b91c1c), bold, line-height 1.8. "A note": blue (#1d4ed8), bold, line-height 1.8. "Plain paragraph": dark grey (#374151), normal weight, line-height 1.8. "Outside paragraph": dark grey, normal weight, the browser's default line height. Both the h1 and the h2 use Georgia.

Tools that keep specificity low

Selectors inside :where() add no specificity at all, so :where(#sidebar) p is only (0,0,1) and a plain p rule written later can override it. :is() instead takes the specificity of its most specific argument. Cascade layers (@layer) order whole groups of rules: normal rules that are not in any layer beat rules inside a layer, whatever their specificity.

low-specificity.css
/* (0,0,1): the ID inside :where() counts for nothing */
:where(#sidebar) p { color: #b91c1c; }
p { color: #1d4ed8; }          /* also (0,0,1) and later: wins */

@layer base {
  p.lead { color: #b91c1c; }   /* (0,1,1), but inside a layer */
}
p { color: #1d4ed8; }          /* unlayered: beats the layer */

In real projects

Where this shows up in real projects

Large teams use naming conventions to avoid specificity wars. BEM (Block, Element, Modifier) uses only single-class selectors such as .card, .card__title and .card--featured, so every rule has specificity (0,1,0) and conflicts are settled by source order alone. Utility frameworks such as Tailwind CSS get the same benefit from single-class rules.

IDs are still used, just not for styling: for in-page links (href="#pricing"), for connecting a form label to its input (for="email") and for JavaScript to find one element. When you must override HTML from a third-party widget or a CMS, check its selector's specificity in DevTools, match it, and load your stylesheet after it; that is far cleaner than !important.

Common mistakes

Common mistakes

1. Forgetting the dot or # in CSS (or adding it in HTML)

Writing note { } in CSS looks for a <note> tag and matches nothing. The reverse, class=".note" in the HTML, makes the class name literally ".note", which the .note selector does not match. Dot in CSS, no dot in HTML.

2. Mixing up .a.b and .a .b

One space changes the meaning completely: .card.featured selects an element with both classes, while .card .featured selects an element inside a .card. If a rule does not match, check in the Elements panel which element actually carries each class.

3. Lengthening selectors to win overrides

A selector like body div.main .content ul li a wins for now, but it breaks as soon as the HTML structure changes slightly, and every later override needs an even longer one. Add a class and keep the selector short.

Best practices

Best practices

  • Give every element you style a class named for its meaning (.price, .nav-link), not its appearance.
  • Use type selectors for base styles such as body, a and h1, and write components with classes.
  • Keep descendant selectors to two levels at most, or they become tightly tied to the HTML structure.
  • Whenever you feel like adding !important, first look in DevTools at which rule is winning.

Mini challenge

Mini challenge: a tea house navigation bar

Without changing the HTML in the starter, and without any ID selector, write rules for it. The link for the current page must stand out from the other links.

  • Give the h1 inside header the Georgia font with a descendant selector
  • Give every link inside nav one colour and a right margin
  • Make the .active link bold and a different colour, beating nav a through specificity (no !important)
  • Make p.note italic without touching the plain paragraph
nav.html
<!-- TODO: wrap in <!DOCTYPE html>, <head> and <body>; add a <style> block -->
<style>
  /* TODO: header h1 - Georgia font */
  /* TODO: nav a - colour + margin-right */
  /* TODO: the .active link inside nav - bold + another colour (beat nav a) */
  /* TODO: p.note - italic */
</style>

<header>
  <h1 id="site-title">Golden Tea House</h1>
  <nav>
    <a href="/">Home</a>
    <a href="/menu" class="active">Menu</a>
    <a href="/contact">Contact</a>
  </nav>
</header>
<p>Open daily from 7 am.</p>
<p class="note">Closed on public holidays.</p>

Expected: The title is in Georgia. All three links are blue with space between them, and the "Menu" link is bold and dark red. "Closed on public holidays." is italic, while the "Open daily" line is unchanged.

Show hint

nav a has specificity (0,0,2). nav a.active is (0,1,2), so it wins wherever it appears in the stylesheet.

Show solution
nav.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Golden Tea House</title>
  <style>
    header h1 {
      font-family: Georgia, serif;
    }
    nav a {
      color: #1d4ed8;
      margin-right: 1rem;
    }
    nav a.active {
      font-weight: bold;
      color: #b91c1c;
    }
    p.note {
      font-style: italic;
    }
  </style>
</head>
<body>
  <header>
    <h1 id="site-title">Golden Tea House</h1>
    <nav>
      <a href="/">Home</a>
      <a href="/menu" class="active">Menu</a>
      <a href="/contact">Contact</a>
    </nav>
  </header>
  <p>Open daily from 7 am.</p>
  <p class="note">Closed on public holidays.</p>
</body>
</html>

Quick quiz 1 / 3

Both #main p { color: red; } and .content p.lead { color: blue; } match the same paragraph. What colour is it?

Quick quiz 2 / 3

There is a single <div class="card featured"> with nothing inside it. Which selector matches it?

Quick quiz 3 / 3

A stylesheet has a:hover { color: red; } first and .nav a { color: blue; } after it. What colour is a link inside .nav while hovered?

What to remember

  • Type (p), class (.note), ID (#intro) and universal (*) selectors plus comma lists pick elements.
  • .a.b is one element with both classes; .a .b is a .b inside an .a.
  • Compare specificity as (ID, class, type) from left to right; on a tie, the later rule wins.
  • Keep specificity low with single-class selectors, and avoid !important and IDs for styling.

CSS cascade and specificity — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Selectors | Thuta Learning