Contents

Frontend Development › CSS

Selector

The pattern that chooses which elements a rule applies to.

Also known as: CSS selectors, selectors, class selector, id selector

A selector is the part of a CSS rule that says which elements the styles apply to.

button { ... }        /* selector */
.card  { ... }

The basic kinds

SelectorMatchesExample
Element (type)Every element of that tagp
ClassElements with that class.card
IDThe element with that id (should be unique)#header
AttributeBy attributeinput[type="email"]
UniversalEverything*

Combining them

PatternMeaning
nav aAny a inside nav (descendant)
ul > lili that is a direct child of ul
h2 + pThe p immediately after an h2
h2 ~ pAny p after an h2, with the same parent
button.primaryA button that also has class primary (no space)
h1, h2, h3Any of these (a list; the rule applies to each)

The space in .card .title versus none in .card.title is a classic source of confusion: the first means “a .title inside a .card”, the second means “one element with both classes”.

.card .title { font-weight: 700; }
.card.featured { border-color: gold; }
a:hover { text-decoration: underline; }      /* pseudo-class: a state */
p::first-line { font-weight: bold; }         /* pseudo-element: a part of an element */

Pseudo-classes (:hover, :focus, :nth-child(2)) select by state or position; pseudo-elements (::before, ::after) select a part of an element.

Habits

  • Prefer classes. They’re reusable and have low specificity.
  • Don’t style by IDs or long chains like div > div > ul li a, which break when HTML changes.
  • Keep selectors short so they’re easy to read and override.
  • In DevTools, the selector for each rule is shown, so you can see which ones match an element, and which lose.

When two rules match the same element and disagree, the winner is decided by the cascade and specificity.