2.2 Selectors: Tag, Class, ID, and Descendant
The first step of any CSS rule is always "who to pick." A selector precisely specifies which elements a style applies to. This section covers the four most common kinds.
The lab below lets you tap different selectors and watch which elements on the right get matched (highlighted) in real time.
Tag selector: pick by tag name
Just write the tag name to select every element of that kind on the page:
p { color: gray; } /* all paragraphs */
h1 { font-size: 32px; } /* all top-level headings */Simple, but sometimes too broad — it picks every <p>.
Class selector: pick by class (the most common)
Add a class attribute to an element, then select it with a dot .. The same class can be used on many elements:
<p class="warning">Warning!</p>
<span class="warning">This is also a warning</span>.warning {
color: red;
font-weight: bold;
}Class selectors are the most-used in everyday CSS because they're both precise and reusable. An element can have several classes at once: class="btn primary".
ID selector: pick by id (unique)
Add an id attribute, then select with a hash #. Key rule: an id may appear only once per page:
<header id="top-bar">…</header>#top-bar {
background: black;
}Descendant selector: pick what's "inside"
Join two selectors with a space to mean "B inside A":
nav a { color: white; } /* only links inside nav */
.card p { margin: 0; } /* only paragraphs inside .card */Note this differs from "pick both A and B" — that uses a comma: h1, h2 { } (selects both h1 and h2).
Selector cheat sheet
| Syntax | Meaning | Example |
|---|---|---|
p | Tag selector: all p | p { } |
.name | Class selector: class includes name | .btn { } |
#name | ID selector: id equals name (unique) | #header { } |
A B | Descendant: B inside A | nav a { } |
A, B | Group: both A and B | h1, h2 { } |