CSS selectors

A selector is the part of a CSS rule before the curly braces: it picks the elements the styles apply to.

Syntax

selector {
  property: value;
}
h1, h2 { … }      /* group */
.card > p { … }   /* child */

Selector types

SelectorWhat it does
*universal: every element
pby tag: every paragraph
.cardby class: elements with class="card"
#mainby id: the element with id="main" (one per page)
[type="email"]by attribute and its value
a:hoverpseudo-class, a state: a link under the pointer
p::first-linepseudo-element, a part of an element: the first line of a paragraph
.card pa descendant at any depth
.card > pa direct child only
h1 + pthe sibling right after
h1 ~ pall following siblings
h1, h2a group: several selectors separated by commas

Example

* { box-sizing: border-box; }
p { margin: 4px 0; }
.card {
  padding: 12px;
  border: 1px solid #94a3b8;
}
.card > p { color: #0284c7; }
h1 + p { font-weight: bold; }
a:hover { color: #dc2626; }
[data-state="new"] { background: #fef3c7; }
<div class="card" data-state="new">
  <h1>Card</h1>
  <p>First paragraph after h1: bold (h1 + p) and blue (.card > p).</p>
  <p>Second paragraph: blue only.</p>
  <div><p>Nested deeper: not blue, it is not a direct child of .card.</p></div>
  <a href="#top">Hover over me</a>
</div>

Result

▶ Open in HTML Editor

Good to know

  • When several rules set the same property, the more specific one wins: a style attribute → #id → .class, [attribute], :pseudo-class → tag. With equal specificity, the one lower in the CSS wins.
  • Classes are more convenient for styling: ids are very specific and hard to override later.
  • A selector reads right to left: .card p means "any p inside .card".

Sources and specification

See also