Codectionary / Developer documentation / CSS

Combinators

Combinators define relationships between selectors. The descendant combinator (space) matches any nested element. The child combinator (>) matches only direct children. The adjacent sibling combinator (+) matches the very next sibling. The general sibling combinator (~) matches all following siblings.

Syntax

A B { }   /* descendant */
A > B { } /* direct child */
A + B { } /* adjacent sibling */
A ~ B { } /* general sibling */

Examples

Descendant vs Child Combinator

The key difference between space and >.

.card p { color: gray; }     /* ANY <p> nested anywhere inside .card, at any depth */
.card > p { color: gray; }   /* ONLY <p> elements that are DIRECT children of .card */

Sibling Combinators

Targeting elements based on their position relative to a sibling.

h2 + p { margin-top: 0; }      /* only the <p> immediately following an <h2> */
input:checked ~ label { color: green; } /* every label after a checked input, at any distance */

Parameters and values

  • (space) (descendant combinator): Matches elements nested anywhere inside, at any depth
  • > (child combinator): Matches only direct (one-level) children
  • + (adjacent sibling): Matches only the immediately following sibling
  • ~ (general sibling): Matches all following siblings, not just the next one

Best practices

  • Use the child combinator (>) when you specifically want to avoid styling deeply nested elements that happen to share a selector
  • Use the adjacent sibling combinator (+) for spacing adjustments, like removing top margin from an element right after a heading
  • The ~ general sibling combinator combined with :checked is a classic CSS-only trick for building interactive components without JavaScript
  • Avoid overly long combinator chains (like .a .b > .c + .d) - they become fragile and hard to maintain as markup changes

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation