Combinators: Descendant, Child, Sibling Selectors
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
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.
| Combinator | Matches |
|---|---|
A + B | The single element B that comes immediately after A |
A ~ B | Every 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.