Sub topic 2
Type, Class, and ID Selectors
This chapter assumes you can read basic HTML (elements, attributes, nesting) and can link or embed a stylesheet. It also assumes you know simple properties such as color and margin. Here you will learn the three selectors you use most, what each one matches, and when to pick which.
What a selector does
A selector is the part of a rule before the braces. It is a test the browser runs against every element in the document. If the element passes, the declarations inside the braces apply to it.
p { margin: 0; }Here p is the selector and margin: 0; is the declaration. The browser checks each element and applies the declaration to every one that is a <p>.
The three basic selectors test different parts of an element:
| Selector | Syntax | Tests | Example |
|---|---|---|---|
| Type | `name` | The element's tag name | `p` |
| Class | `.name` | A token in the `class` attribute | `.note` |
| ID | `#name` | The value of the `id` attribute | `#main` |
Type selectors
A type selector is an element name written without any punctuation. It matches every element of that type.
p { margin: 0; }
h2 { font-size: 1.5rem; }Type selectors are good for baseline styles that should hold across the whole page. In an HTML document, element names are case-insensitive, so P and p match the same elements. Write them in lowercase anyway, because that is the convention.
A type selector says nothing about where an element sits or what role it plays. p { color: gray; } styles every paragraph, including ones in the footer, in a sidebar, and inside a widget someone else wrote. That reach is useful for defaults and risky for anything specific.
Class selectors
A class selector is a dot followed by a class name. It matches any element whose class attribute contains that name.
.note { color: #555; }The class attribute holds a space-separated list. An element can carry several classes, and the selector matches if any one token equals the name:
<p class="note">One class.</p>
<p class="note important">Two classes.</p>
<div class="note">Not a paragraph, still matches.</div>All three elements match .note. The class selector ignores the element type, and the same class can appear on many elements. That makes classes the main tool for reusable styling.
Class names follow some rules:
- Matching is exact against whole tokens.
.notedoes not matchclass="footnote"orclass="notes". - Matching is case-sensitive in standards mode.
.Notedoes not matchclass="note". - A name cannot start with a digit unescaped.
.2colis invalid, while.col-2is fine. If you inherit markup with a numeric class, you can escape it as.\32 col, but renaming the class is better. - Hyphens and underscores are allowed, so
.card-titleand.card_titleare both valid.
ID selectors
An ID selector is a hash followed by an ID value. It matches the element whose id attribute equals that value.
#main { max-width: 60rem; }<main id="main">...</main>IDs are meant to be unique. An id must appear on only one element per document, and it cannot contain whitespace. The same value is used by fragment links (<a href="#main">), by <label for="...">, and by document.getElementById.
If you break uniqueness, CSS still applies the rule to every element carrying that ID. The browser does not complain. JavaScript, though, usually finds only the first one, so duplicates produce bugs far from the stylesheet. Validators flag duplicate IDs as errors.
IDs also carry much more weight than classes when rules conflict. A rule using #main beats a rule using .note even if the class rule comes later. The next chapters explain how to calculate this. For now, remember it as the reason many teams use IDs for JavaScript and in-page links, and classes for styling.
Combining them into compound selectors
You can chain simple selectors with no spaces between them. The result matches only elements that satisfy every part. This is a compound selector.
p.note { color: blue; }
.note.important { font-weight: bold; }
div#main.wide { max-width: none; }p.notematches paragraphs that also have the classnote..note.importantmatches any element with both classes.div#main.widematches adivwith the IDmainand the classwide.
If a type selector is present, it must come first. .notep would be read as one class name, and .note p (with a space) means something different, which the combinators chapter covers.
The space is the most common source of mistakes in this area:
.card .title { color: red; } /* a .title somewhere inside a .card */
.card.title { color: red; } /* one element with both classes */These look nearly identical and match entirely different elements.
A worked example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selectors demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main id="main">
<h2>Notes</h2>
<p>A plain paragraph.</p>
<p class="note">A note.</p>
<p class="note important">An important note.</p>
<div class="note">A note inside a div.</div>
</main>
</body>
</html>p { margin: 0 0 1rem; }
.note { color: #555; }
p.note { border-left: 4px solid #999; padding-left: 0.5rem; }
.note.important { font-weight: bold; }
#main { max-width: 60rem; margin: 0 auto; }Trace what each element receives:
- The plain paragraph matches only
p, so it gets the margin. - The first note paragraph matches
p,.note, andp.note. It gets the margin, the gray text, and the left border. - The important note matches those same three rules plus
.note.important, so it is also bold. - The
divmatches only.note. It is gray but has no border, becausep.noterequires a paragraph. - The
mainelement matches#mainand gets the width limit.
An element usually matches many rules at once. The browser merges all of them, and it only has to decide between rules when they set the same property.
Choosing between them
Use these as defaults:
- Type selectors for site-wide baselines such as body text, headings, and links.
- Class selectors for nearly everything else. They are reusable, they carry a meaningful name, and their weight is moderate.
- ID selectors only when you need to target one specific, unique element and cannot add a class. Prefer a class where you can, because an ID rule is hard to override later.
Name classes after purpose, not appearance. .warning survives a redesign. .red-text becomes false the day the warning turns orange.
Common errors
- Forgetting the dot or hash.
note { ... }is a type selector for a<note>element, which does not exist, so the rule silently does nothing. CSS does not report that a selector matched nothing. - Wrong case.
.Notewill not matchclass="note". - Space versus no space.
.a .band.a.bdiffer, as shown above. - Duplicate IDs. The CSS applies to all of them, but scripts and fragment links behave unpredictably.
- Class tokens that merely look similar.
.btndoes not matchclass="btn-primary". If you want both classes, put both on the element:class="btn btn-primary". - Invalid selector in a list. If one selector in a comma-separated list is invalid, the whole rule is dropped. Keep each selector valid, and check names that start with digits.
Exercise
Given <p id="intro" class="note big">Hi</p> and <div class="note">Yo</div>, which elements does each selector match: p, .note, .note.big, #intro, p.note, and .note p?
Show answer
p matches the paragraph only. .note matches both elements. .note.big matches only the paragraph, because only it has both classes. #intro matches only the paragraph. p.note matches the paragraph only. .note p matches neither, because it needs a <p> nested inside an element with the class note, and the paragraph here is not inside anything with that class.
Exercise
A stylesheet has .alert { color: red; }, but the element <p class="Alert">Careful</p> is not red. Give the cause and two ways to fix it.
Show answer
Class matching is case-sensitive in standards mode, so .alert does not match the token Alert. Fix it by changing the markup to class="alert", or by changing the selector to .Alert. Matching the case of the markup is usually the smaller change, and consistent lowercase names avoid the problem.