CSS Combinators
A CSS combinator is a symbol between selectors that selects by relationship. A space, >, +, and ~ each name a different relationship.
Descendants at any depth
A space selects descendants at any depth. The paragraph inside the box turns blue, and the demo paragraph stays black.
.box p {
color: blue;
}Direct children only
The > symbol selects direct children. The h2 sits directly inside the box.
.box > h2 {
color: green;
}The next sibling
Siblings share the same parent. The + symbol selects the paragraph right after the heading, and no other paragraph.
h1 + p {
color: red;
}All later siblings
The ~ symbol selects every later sibling. Every paragraph after the heading turns blue, including the demo paragraph.
h1 ~ p {
color: blue;
}Example
.box p {
color: blue;
}
h1 + p {
color: red;
}
ul li {
color: green;
}Key points
- Descendant selector: a space between selectors, matching at any depth
- Child selector: a > between selectors, matching one level down
- Adjacent sibling selector: a + between selectors, matching the next sibling
- General sibling selector: a ~ between selectors, matching all later siblings
- Sibling selectors only look forwards to later siblings.
In this example, the descendant selector .box p colours the paragraph inside the box. The adjacent sibling selector h1 + p colours the intro paragraph red. The descendant selector ul li colours every list item green. Each combinator follows a different relationship.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which symbol selects a direct child?