Combinators: Descendant, Child, Sibling Selectors

Descendant Combinator (Space)

A space between two selectors matches an element that sits anywhere inside another, no matter how deeply nested.

.card p {
  color: #555555;
}

This matches every <p> inside an element with class card, whether it is a direct child or nested several levels deeper.

Child Combinator (>)

The greater-than sign restricts the match to direct children only, ignoring anything nested further down.

.card > p {
  color: #555555;
}

Here, a <p> wrapped inside another <div> that sits inside .card would not match, because it is a grandchild, not a direct child.

Sibling Combinators (+ and ~)

Sibling combinators match elements that share the same parent as a reference element.

CombinatorMatches
A + BThe single element B that comes immediately after A
A ~ BEvery B that comes after A and shares the same parent
h2 + p {
  margin-top: 0;
}

h2 ~ ul {
  color: #888888;
}

The first rule removes top margin only from a paragraph that directly follows a heading. The second rule styles every list that comes anywhere after a heading, as long as they are siblings.

Why Combinators Matter

Combinators let a stylesheet describe relationships in the document instead of adding a class to every single element. Used carefully they keep markup cleaner, but overly long combinator chains can also make styles fragile and hard to trace - a simple class is often clearer once a selector gets more than two or three levels deep.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.