CSS Basics›Core· 40 min read
CSS Selectors
Selectors decide WHICH elements get styled. Master these five and you can target anything.
What you will learn
- Use element, class, id and universal selectors
- Group selectors to share styles
- Choose the right selector for the job
The five you need most
| Selector | Targets | Example |
|---|---|---|
p | All elements of that tag | p { } |
.class | All elements with that class | .card { } |
#id | The one element with that id | #header { } |
* | Every element (universal) | * { } |
a, b, c | Several selectors at once (grouping) | h1, h2, p { } |
<style>
* { font-family: sans-serif; } /* everything */
h1 { color: #4338ca; } /* all h1 */
.highlight { background: #fde68a; } /* class hook */
#special { color: crimson; } /* one element */
p, li { color: #5b6178; } /* grouped */
</style>
<h1>Heading</h1>
<p>A normal paragraph.</p>
<p class="highlight">I have the highlight class.</p>
<p id="special">I am the special one.</p>
<ul><li>A list item</li></ul>Live preview
Match each rule to what changed on screen:
*(universal) gave everything a sans-serif font — even the list item.h1(element) coloured the heading indigo, because it targets every<h1>tag..highlight(class) gave the second paragraph a yellow background — it only hit the element withclass="highlight".#special(id) turned the third paragraph crimson — an id targets the one element with that exactid.p, li(grouping) coloured both paragraphs and the list item grey in a single rule — the comma means “apply to all of these”.
Note: The takeaway: a tag name styles all of that tag, a .dot styles a reusable class, a #hash styles one unique element, * styles everything, and commas let one rule cover several targets.
Tip: Remember the prefixes: . for class (reusable, the one you use most) and # for id (unique). The class is your everyday tool.
Note: You will meet more powerful selectors later — combinators (div p), attribute selectors ([type="text"]) and pseudo-classes (:hover). These five are the foundation.
Q. How do you select all elements with class="btn"?
Answer: A class selector uses a dot: .btn. A # selects an id; no prefix selects a tag name.
✍️ Practice
- Style all paragraphs one colour, then override one special paragraph using an
id. - Create a
.cardclass and apply it to three different elements so they share a style. - Use grouping to give
h1,h2andh3the same colour in one rule.
🏠 Homework
- Take your HTML profile page and add classes to the elements you will want to style, then write selectors for each.