Skip to content
KodeTrail

Camp 1 · Step 3 of 13

Selectors

Element, class, and id selectors — plus combining them — so your rules hit exactly the right targets.

14 min+50 XP

A rule is only as good as its aim. Selectors are how CSS takes aim, and three kinds cover almost everything you'll ever write.

Element selectors

Target every element of a kind:

p    { line-height: 1.6; }
h2   { color: darkslategray; }

Class selectors — the workhorse

Add class="…" to any HTML elements, then target them with a dot:

CSS
Live preview

Classes are reusable — any number of elements can share one — and one element can wear several classes: class="highlight rounded". Real-world CSS is overwhelmingly class-based.

ID selectors — one per page

An id must be unique on the page; target it with #:

#site-logo { width: 120px; }

IDs also serve as link anchors (href="#summary"), which is the better reason to use them. For styling, prefer classes — uniqueness makes IDs rigid.

Combining selectors

CSS
Live preview
  • article p — descendant: p anywhere inside article
  • h1, h2 — grouping: both selectors, same rule
  • p.highlight — a p that also has the class
Checkpoint

Which selector targets elements with class="card"?

Checkpoint

What does the selector: nav a { … } target?