Selectors

How CSS Finds the Elements to Style

Selectors

Type, class, id, attribute, pseudo-class, combinators — the toolkit for matching elements.

5 min read Level 1/5 #css#selectors
What you'll learn
  • Use type, class, id, attribute, and descendant selectors
  • Combine selectors
  • Use pseudo-classes and pseudo-elements

A selector picks which elements a rule applies to. Master a handful and you’ve got most of CSS.

The Basics

SelectorMatches
h1All <h1> elements
.cardAll elements with class="card"
#navThe element with id="nav"
*Everything
[type="email"]Inputs with type="email"
[data-state]Anything with a data-state attribute
h1               { color: tomato; }
.card            { padding: 1rem; }
#nav             { position: sticky; }
[type="email"]   { font-style: italic; }

Combinators

Combine selectors to navigate the tree.

CombinatorMeaning
A BB is a descendant of A (any depth)
A > BB is a DIRECT child of A
A + BB is the IMMEDIATELY following sibling
A ~ BB is any following sibling
.card h2         { color: tomato; }   /* any h2 inside .card */
.card > h2       { color: tomato; }   /* direct child h2 only */
h2 + p           { font-size: 1.1rem; } /* the first p after an h2 */

Multiple Selectors (Same Rule)

Comma-separate to apply one rule to many selectors:

h1, h2, h3 {
  font-family: "Inter", sans-serif;
}

Pseudo-Classes — State Selectors

Pseudo-classWhen it matches
:hoverMouse is over the element
:focusElement has focus
:focus-visibleFocused via keyboard (better than :focus)
:activeBeing clicked
:checkedA checked checkbox/radio
:disabled / :enabledForm state
:first-childFirst among its siblings
:last-childLast among its siblings
:nth-child(2n)Even children (or any formula)
:not(.x)Anything NOT matching .x
:is(.x, .y)Anything matching .x OR .y
:has(.x)Has a .x descendant
a:hover           { text-decoration: underline; }
button:focus-visible { outline: 2px solid blue; }
li:nth-child(odd) { background: rgb(0 0 0 / 5%); }
input:not([type="hidden"]) { display: block; }

Pseudo-Elements — Style Bits of an Element

Pseudo-elementWhat it is
::beforeInserted before the element’s content
::afterInserted after the element’s content
::first-lineThe first line of text
::first-letterThe first character
::placeholderAn input’s placeholder text
::selectionSelected text
.required::after { content: " *"; color: red; }
::selection      { background: yellow; }

(Two colons :: is the modern syntax. Single colon still works for the originals.)

Attribute Selectors With Patterns

a[href^="https://"]   { /* starts with https:// — external link */ }
a[href$=".pdf"]       { /* ends with .pdf */ }
a[href*="example"]    { /* contains "example" */ }

Up Next

When multiple rules match the same element, who wins? The cascade.

The Cascade →