Tag, Class & Id Selectors · CSS
Ch 1 · Styling Basics — card 2 of 3.
The selector is the part of a rule before the curly braces. It decides which elements the rule applies to. Picking the right selector means you can style one element, a handful, or every element of a kind.
- 🏷️ Tag selectors that style every matching element
- 🎨 Class selectors that style any element you label
- 🆔 Id selectors for one unique element, and grouping selectors with commas
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Page</title>
<style>
body { font-family: system-ui, sans-serif; }
p { color: #334155; }
.fact { background: #fef3c7; padding: 6px; }
#title { color: #7c3aed; }
h1, h2 { text-align: center; }
</style>
</head>
<body>
<h1 id="title">Space Facts</h1>
<p>The Sun is a star.</p>
<p class="fact">A day on Venus is longer than its year.</p>
<p>Mars has two moons.</p>
<h2 class="fact">Jupiter is the biggest planet.</h2>
</body>
</html>p styles every paragraph. .fact starts with a dot and styles anything with class="fact", so a paragraph and a heading can share it. #title starts with a hash and styles the single element with id="title". Writing h1, h2 with a comma applies one rule to both tags, which saves repeating yourself.
- Tag = p, class = .name, id = #name
- A class can be reused on many elements; an id should appear only once
- An element can have several classes separated by spaces, like class="fact big"