Combinators
Select elements based on their relationship to others.
Syntax
div > p { } h2 + p { }Combinators describe the relationship between selectors:
| Combinator | Meaning |
|---|---|
A B | B inside A (descendant) |
A > B | B is a direct child of A |
A + B | B immediately follows A |
A ~ B | B is a sibling after A |
Example
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.
.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.
.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.
h2 + p {
margin-top: 0;
color: #666;
font-size: 1.1rem;
}
p + p {
margin-top: 1em;
}
Discussion