CSS + vs ~ Sibling Combinators - Adjacent and General
Compare CSS adjacent sibling (+) and general sibling (~) combinators. Style the next element, all following siblings, and build CSS-only toggle patterns.
Detailed Explanation
Two Sibling Combinators
CSS has two combinators that reach sideways in the DOM tree:
| Combinator | Meaning |
|---|---|
A + B |
The first B immediately following A |
A ~ B |
Every B that comes after A (not necessarily adjacent) |
Both require A and B to share the same parent. Neither can look backward.
Adjacent Sibling (+)
<h2>Section</h2>
<p>First paragraph (matched by h2 + p)</p>
<p>Second paragraph (NOT matched)</p>
h2 + p {
margin-top: 0;
font-size: 1.1em;
}
Use it for "the thing right after a heading" patterns: lead paragraphs, captions, definition pairs.
General Sibling (~)
<h2>Section</h2>
<p>First (matched)</p>
<ul>...</ul>
<p>Second (also matched)</p>
h2 ~ p {
color: #555;
}
Every <p> after the <h2>, regardless of intervening elements, gets the rule.
CSS-Only Toggles
The general sibling combinator powers checkbox-driven UI:
<input type="checkbox" id="menu-toggle">
<label for="menu-toggle">Menu</label>
<nav class="drawer">…</nav>
.drawer { transform: translateX(-100%); transition: transform .2s; }
#menu-toggle:checked ~ .drawer { transform: translateX(0); }
Because .drawer follows the checkbox, ~ reaches it without needing a wrapper.
Why You Can't Look Backward
There's no A < B combinator (yet). The closest replacement is B:has(+ A) or B:has(~ A) from the :has() family — modern browsers only.
Specificity
Sibling combinators add no specificity of their own. .menu + p has specificity (0, 1, 1) — one class plus one type.
Use Case
Use + when you only want to style the immediately-following element (heading-to-lead-paragraph spacing, label-after-input pairs). Use ~ for broader "everything after this point" rules and for the classic CSS-only checkbox-hack toggles, modal triggers, and tab interfaces.