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

Try it yourself
Result

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

Try it yourself
Result

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

Try it yourself
Result

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

Try it yourself
Result

* 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

Try it yourself
Result

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

Try it yourself
Result

Commas separate independent selectors that share the same declarations.

Selector cheat sheet

SelectorMatches
pAll <p> elements
.cardElements with class "card"
#headerThe element with id "header"
*Every element
p.leadParagraphs with class "lead"
h1, h2Both h1 and h2 elements

The next lessons add combinators (relationships between elements), attribute selectors, pseudo-classes (states) and pseudo-elements (parts of elements).

Try it yourself

Try it yourself
Result