Combinators

Select elements based on their relationship to others.

Syntaxdiv > p { } h2 + p { }

Combinators describe the relationship between selectors:

CombinatorMeaning
A BB inside A (descendant)
A > BB is a direct child of A
A + BB immediately follows A
A ~ BB is a sibling after A

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer uses a descendant combinator to style only the links inside .nav, leaving other page links unaffected.
  • A designer uses the adjacent sibling combinator to add top margin to a p that immediately follows an h2, creating visual breathing room.
  • A developer uses the child combinator on .menu > li to style only direct list items, not nested sub-menu items.

More examples

Descendant combinator for nav links

Selects every a element anywhere inside .nav using the descendant (space) combinator.

Example Β· css
.nav a {
  color: #fff;
  text-decoration: none;
  padding: 8px 12px;
}

Child combinator for direct items

The > combinator targets only direct li children of .menu, leaving nested sub-menu items unaffected.

Example Β· css
.menu > li {
  display: inline-block;
  border-bottom: 2px solid transparent;
}
.menu > li:hover {
  border-bottom-color: #2965f1;
}

Adjacent sibling for spacing

Uses + to target a p immediately after h2 (removing its top margin) and to space consecutive paragraphs apart.

Example Β· css
h2 + p {
  margin-top: 0;
  color: #666;
  font-size: 1.1rem;
}
p + p {
  margin-top: 1em;
}

Discussion

  • Be the first to comment on this lesson.
Combinators β€” CSS | SoundsCode