CSS Combinators

Combinators are the symbols between selectors that describe how elements must be related for a rule to match.

A single selector targets elements on its own, but a combinator connects two selectors so that a rule only applies when the elements have a certain relationship in the document tree, such as parent, child, or sibling.

The four combinators

CombinatorNameMatches
A BDescendant (space)Any B inside A, at any depth
A > BChildAny B that is a direct child of A
A + BAdjacent siblingThe B immediately after an A
A ~ BGeneral siblingEvery B that follows an A, same parent

Descendant vs child

Space vs the child combinator

<!DOCTYPE html>
<html>
<head>
<style>
/* Any <a> anywhere inside a nav */
nav a {
  color: navy;
}

/* Only <li> that are direct children of <ul> */
ul > li {
  margin: 4px 0;
}
</style>
</head>
<body>

<nav>
  <div><a href="#">Deep link</a></div>
</nav>

<ul>
  <li>Direct child</li>
  <li>Direct child</li>
</ul>

</body>
</html>

The descendant combinator reaches all the way down through nested elements, while the child combinator stops at the first level, ignoring any more deeply nested matches.

Sibling combinators

Adjacent and general siblings

<!DOCTYPE html>
<html>
<head>
<style>
/* The paragraph right after a heading */
h2 + p {
  margin-top: 0;
}

/* Every paragraph after a heading */
h2 ~ p {
  color: #555;
}
</style>
</head>
<body>

<h2>Section title</h2>
<p>This paragraph sits right after the heading.</p>
<p>This paragraph comes later but still follows the heading.</p>

</body>
</html>
Note: Sibling combinators only look forward, at elements that come after the first one in the HTML, and both elements must share the same parent.
Note: Combinators pair well with pseudo-classes; for example, ul > li:first-child styles just the first direct child of a list.

Exercise: CSS Combinators

What does the descendant combinator (a single space) select?