Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Selectors and How Rules Find Elements

Read any selector as a description of elements, use combinators, pseudo-classes and pseudo-elements deliberately, and predict exactly which elements a rule will style.

Contentsand lesson path

What you will learn

  • Predict which declaration wins using origin, cascade layers, specificity, source order and inheritance, and resolve conflicts without !important.

Prerequisites: Semantic HTML

01. Why it matters

Every stylesheet is a list of promises: when elements look like this, style them like that. The "when elements look like this" half is the selector, and it is the part of CSS you use most and think about least. A selector is a description of elements — a pattern the browser matches against every element in the page, top to bottom, every time the document changes.

Reading selectors fluently is the difference between styling on purpose and styling by trial and error. When a rule styles more than you expected, or nothing at all, the explanation is often in the selector, or in the cascade that the next lesson covers, rather than in the properties. And selector choice has a second consequence that this skill returns to in the next lesson: the more specific a selector is, the harder it is to override later.

This lesson covers the selectors you will meet daily: simple selectors, combinators that describe relationships, attribute selectors, and the pseudo-classes and pseudo-elements that match states and parts of elements.

02. Simple selectors: type, class and id

A type selector (p, h2, button) matches every element of that kind in the document. Use it for defaults that should genuinely apply everywhere — the base styles of a design. A class selector (.note) matches every element whose class attribute contains that name, and an element can carry several classes at once. Classes are the workhorse of CSS because they describe meaning rather than structure: .warning can be a paragraph today and a list item tomorrow. An id selector (#signup) matches the single element with that id, and a page should never repeat an id. Because ids are unique by definition, they are tempting for styling one-offs, but they make rules very hard to override — the next lesson quantifies exactly why.

A compound selector like aside.note matches elements satisfying every part at once: an <aside> element that also has the note class. Adding parts narrows the match; it never widens it.

03. Combinators and attributes

Combinators join simple selectors to describe relationships in the document tree:

  • article p (space) is the descendant combinator: any p anywhere inside an article, at any depth.
  • article > p is the child combinator: only p elements whose parent is the article.
  • h2 + p is the next sibling combinator: a p immediately following an h2. This is how you style a lead paragraph without adding a class to it.
  • h2 ~ p is the subsequent sibling combinator: every p that follows the h2 at the same nesting level, not just the next one.

Attribute selectors match elements by what their attributes contain. [href^="https"] matches links whose href starts with https, [type="checkbox"] matches exactly that input, and [data-state="open"] is the standard way to style the state of a component. They read like small queries, which is exactly what they are.

04. Pseudo-classes and pseudo-elements

A pseudo-class, written with one colon (:hover, :focus-visible, :nth-child(2)), matches elements in a state or position that no attribute could express: which element the pointer is over, which one has keyboard focus, which is the second child. :focus-visible deserves a habit-forming mention: it matches only when the browser decides the focus indicator should be visible, typically for keyboard users, so styling it rather than :focus keeps mouse clicks from showing rings.

A pseudo-element, written with two colons (::before, ::after, ::first-line), styles a part of an element rather than the whole thing. ::before and ::after can insert generated content through the content property.

Three modern selectors round out the set. :is(h2, .standfirst) matches anything any of its arguments matches, and its specificity is that of its most specific argument. :where(...) matches the same elements but always contributes zero specificity, which makes it safe to include in shared defaults. :has(...) styles a parent based on its content — article:has(img) matches articles containing an image. Such a parent selector has worked in every major browser engine only since December 2023 (Baseline Newly available then, Widely available since June 2026), so check your audience before relying on it.

05. Watching matching happen

HTML · index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Book review</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <article class="review">
    <h2>The Long Field</h2>
    <p class="standfirst">A study of hedgerows.</p>
    <p>Hedgerows hold the lanes together.</p>
    <ul>
      <li>Chapter one: the hedge</li>
      <li>Chapter two: the bank</li>
      <li>Chapter three: the verge</li>
    </ul>
    <p>More from <a href="https://example.com/field">the author</a>.</p>
  </article>
</body>
</html>
CSS · styles.css
.review { border: 1px solid #cccccc; }
.review > p { margin: 0 0 12px; }
.standfirst { font-style: italic; }
li:nth-child(2) { font-weight: bold; }
a[href^="https"] { color: teal; }
.review h2::after { content: " - review"; }
:is(h2, .standfirst) { color: darkslategray; }

Paste this into the browser console on that page and document.querySelectorAll counts the elements each selector matches:

DevTools console
const selectors = ['.review', '.review > p', 'li:nth-child(2)',
  'a[href^="https"]', ':is(h2, .standfirst)', '.review h2::after'];
for (const sel of selectors) {
  console.log(sel + ' -> ' + document.querySelectorAll(sel).length +
    ' match(es)');
}
Expected output
.review -> 1 match(es)
.review > p -> 3 match(es)
li:nth-child(2) -> 1 match(es)
a[href^="https"] -> 1 match(es)
:is(h2, .standfirst) -> 2 match(es)
.review h2::after -> 0 match(es)

Read the counts back against the markup. .review > p matches the two plain paragraphs and the standfirst but not the list items, because the list is not a p — the child combinator checked depth, not styling. li:nth-child(2) matches one item, and it is the one you expect only because the list has no other element children; :nth-child() counts all siblings of any type, while :nth-of-type() counts siblings of the same type. :is(h2, .standfirst) matches two elements, one per argument. And the last line is the quiet lesson: querySelectorAll reports zero matches for ::after even though the styled text appears on screen, because pseudo-elements are not elements at all — they are boxes the renderer hangs off a matched element, visible in the DevTools Elements panel as ::after but absent from the DOM. A rule "not matching" and a rule "matching invisibly" are different failures, and knowing which one you have saves an hour of guesswork.

06. Check your understanding

Practice check · 3 questions

Predict the matches

For each situation, predict what the selector matches before reading the answer.

Q1. In `<ul><li>first</li></ul><p>note</p>`, which elements does `ul + p` match?
Q2. A shared stylesheet has `:is(#promo, .banner) { color: crimson; }`. Why is `:where(#promo, .banner)` a safer choice for defaults?
Q3. You added `.card::after { content: "New"; }` but `document.querySelectorAll(".card::after")` finds nothing. What is true?
Practice only: not graded, not saved, not evidence.

07. Apply it

Open your semantic article page from the semantic-html skill and put a stylesheet beside it. Write six rules, each with a different tool: one type selector for base text, one class, one id, one descendant or child combinator, one attribute selector, and one :focus-visible rule that gives visible links and buttons a clear outline. Then, in the console, run document.querySelectorAll on each selector and check the counts against what you meant to style. Where the count surprises you, read the selector aloud as a sentence and rewrite it until the sentence says what you want. Keep the selectors you end up with — the next lesson uses them to explain why one of them will be hard to override.

08. Review prompt

Without looking back: what do article p, article > p, article + p and article ~ p each match? Why does a compound selector narrow a match while a class list on an element can only ever add matches? And what is the difference between :nth-child(2) and :nth-of-type(2), between :hover and :focus-visible, and between ::after and :after in a stylesheet that must also serve old browsers?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check