CSS Combinators
Learn how CSS combinators select elements according to their relationships in the document tree.
Basic
What combinators do
CSS combinators express relationships between selectors. Instead of matching an element only by its own type, class, or ID, a combinator can select an element according to where it appears relative to another element in the document tree.
| |
Here, the space between
.card and
p is the descendant combinator. It matches paragraph elements that are descendants of an element matched by
.card.
Descendant combinator
A descendant combinator is represented by whitespace between two selectors. The second selector can match an element at any depth below an element matched by the first selector.
| |
Child combinator
The child combinator uses
> to require a direct parent-child relationship. This is narrower than a descendant selector because deeper descendants do not match.
| |
Sibling combinators
The next-sibling combinator
+ matches an element immediately preceded by the first selector. The subsequent-sibling combinator
~ matches later siblings of the same parent, even when other elements occur between them.
| |
Combining combinators with selectors
Output
Ready to run.
Combinators can be combined with type, class, ID, attribute, and other selectors to express more precise relationships.
| |
Choose the relationship you mean
Use the least broad relationship that expresses the rule you actually need. If a direct child is required, prefer the child combinator instead of a descendant selector. If adjacency matters, use the next-sibling combinator rather than the broader subsequent-sibling relationship.
CSS also defines a column combinator in Selectors Level 4, but it is currently marked at risk in the W3C draft and is not supported by browsers, so it is outside this beginner learning resource.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.