Selectors
Selectors decide which elements a rule applies to. The basic ones — type, class, id and universal — cover most everyday styling. Combined with grouping, they let you target exactly the elements you want without touching the HTML.
Type selector
A type (or element) selector matches every element with that tag name. It's ideal for base styles, like the default look of all paragraphs or headings.
Class selector
A class selector starts with a dot and matches any element whose class attribute contains that name. Classes are the workhorse of CSS: reusable, combinable and easy to understand.
ID selector
An id selector starts with # and matches the one element with that id. IDs are very "specific" — they override class styles in a way that's hard to undo — so most developers prefer classes for styling and keep ids for links and JavaScript.
Universal selector
* matches every element. It's commonly used for small resets, such as box-sizing (lesson 17), and for debugging layouts by outlining everything.
Combining selectors on one element
Writing selectors together with no space means "both at once": p.note is a paragraph that also has class note; .button.primary is an element with both classes.
Grouping
Commas separate independent selectors that share the same declarations.
Selector cheat sheet
| Selector | Matches |
|---|---|
p | All <p> elements |
.card | Elements with class "card" |
#header | The element with id "header" |
* | Every element |
p.lead | Paragraphs with class "lead" |
h1, h2 | Both h1 and h2 elements |
The next lessons add combinators (relationships between elements), attribute selectors, pseudo-classes (states) and pseudo-elements (parts of elements).