CSS Selectors Explained: Type, Class, ID and More
A declaration is only useful if it lands on the right elements. Selectors are the targeting language of CSS, and the same syntax is used by JavaScript's document.querySelector(), so learning it pays off twice.
The three basic selectors
- Type selector:
pmatches every<p>element. - Class selector:
.warningmatches every element whoseclassattribute contains the wordwarning. An element can carry several classes, likeclass="card warning", and match both.cardand.warning. - ID selector:
#signupmatches the single element withid="signup". IDs must be unique in a page, which makes them a poor fit for reusable styles. Most styling is done with classes.
You can chain them without spaces to require all conditions at once: p.warning means "a <p> that also has the class warning", and .card.featured means an element with both classes.
Attribute selectors
Square brackets match on attributes. [disabled] matches any element that has a disabled attribute at all. a[href^="https"] matches links whose href starts with https, $= means ends with and *= means contains. These are great for styling external links or PDF downloads without adding classes.
Combinators: relationships
A space between two selectors is the descendant combinator: nav a matches every link anywhere inside a <nav>. The > sign is the child combinator and is stricter: ul > li only matches list items that are direct children of the list. h2 + p matches a paragraph immediately after an h2, and h2 ~ p matches every later sibling paragraph.
The example styles a small menu using all of these. The script counts how many elements each selector matches, using the same selector strings, so you can check your understanding against the browser.
Expected page text
Menu Pick a page. Home Partner site Guide (PDF) nav a matches 3 ul > li matches 3 .item.active matches 1 a[href^="https"] matches 1 a[href$=".pdf"] matches 1 h2 + p matches 1
Try changing ul > li to ul li: the count stays the same here because every li is a direct child. Add a nested list and the two would differ.
Grouping
A comma lets several selectors share one block: h1, h2, h3 { font-family: Georgia, serif; }. Each part of the list is independent, so h1, .title means "every h1, and also every element with class title".
Common mistakes
- Writing
.card .featured(with a space) when you meant.card.featured. The space turns it into "a.featuredelement inside a.card". - Using the same
idon several elements. The page still renders, but scripts and anchors will only find the first one. - Forgetting the dot:
warning { }looks for a<warning>element, which does not exist.
Summary
p,.classand#idare the core selectors; chain them to combine conditions.[attr],^=,$=and*=target attributes.- Space,
>,+and~express relationships; commas group selectors.
Quiz: Selectors