Styling is only useful if you can target the right elements. Selectors are how you point CSS at exactly what you want — one element, a whole group, or elements inside others. You will use these constantly.
The three core selectors
A type selector targets every element of a kind. A class selector (a dot) targets any element carrying that class and can be reused. An id selector (a hash) targets the single element with that id.
| Selector | Example | Targets |
|---|---|---|
| Type | p | All <p> elements |
| Class | .note | Any element with class="note" |
| Id | #lead | The one element with id="lead" |
| Group | h1, h2 | Both h1 and h2 |
| Descendant | nav a | Links inside a nav |
<p id="lead">Lead paragraph.</p>
<p class="note">A note.</p>
<p>Normal.</p>p { color: #444; }
.note { background: #fff3cd; padding: 6px; }
#lead { font-weight: bold; }Grouping and descendant selectors
Apply one rule to several selectors by separating them with commas. Target nesting with a space — <code>.card p</code> means "paragraphs inside .card".
<h1>Title</h1>
<div class="card"><p>Inside card</p></div>
<p>Outside</p>h1, h2 { font-family: sans-serif; }
.card p { color: #2563eb; }Classes vs ids
- Reusable on many elements
- Targeted with .name
- Use for styling
- The everyday choice
- Unique — one per page
- Targeted with #name
- Use as a unique hook
- Use sparingly
<div id="card">…</div>\n<div id="card">…</div><div class="card">…</div>\n<div class="card">…</div>Reusing the same id on multiple elements is invalid and breaks styling and scripts. Use a class when you need it more than once.
Favour classes for styling. They are reusable and keep specificity low and predictable. Reserve ids for unique anchors and JS hooks.
Create a class called "highlight" with a yellow background, apply it to two paragraphs, and give one heading an id with a different colour.
1. How do you target a class?
2. What does "nav a" select?
3. How many times can an id be used per page?
- Core selectors: type (p), class (.note), id (#lead).
- Group with commas; target nesting with a space.
- Classes are reusable; ids must be unique.
- Prefer classes for styling to keep specificity low.