22 min read
Selectors
Element, class, id, grouping and descendant selectors, a first look at :hover, and which rule wins (specificity).
The Basic Selectors
| Selectors | ||
|---|---|---|
What the browser shows
Try it: Add a rule
p { color: grey; }. Which paragraph changes? Then add class="note" to the first paragraph in the HTML.Class or ID?
Class vs id
| Class (.name) | ID (#name) |
|---|---|
| Can be used on many elements | Must be unique — one per page |
An element can have several: class="card featured" | An element has at most one id |
| Use for styling groups of things | Use for link targets (#credits) and one-off parts |
Which Rule Wins? Specificity
When two rules set the same property on the same element, the more specific selector wins:
inline style > #id > .class (and :hover) > element
If they are equally specific, the later rule wins.
Working out the winnerCSS
p { color: black;} .note { color: grey;}For <p class="note">, both rules match. .note is a class selector, which beats the element selector p — so the text is grey, even if the p rule came later.
Practice
Which selector styles every element with class="card"?
Choose one.
More lessons in CSS · Next: Colours and Backgrounds · Previous: How CSS Works
