CSS General Sibling Selector (A ~ B) — All Following Siblings
Learn the CSS general sibling combinator (~) that targets all sibling elements following a reference element. Understand the difference from the adjacent sibling selector.
Detailed Explanation
CSS General Sibling Selector
The general sibling combinator (~) selects all sibling elements that follow a reference element, regardless of whether they are immediately adjacent.
Syntax
/* Select all <p> elements that come after an <h2>,
as long as they share the same parent */
h2 ~ p {
color: #555;
}
How It Works
<div>
<p>Before heading</p> <!-- NOT matched (comes before h2) -->
<h2>Title</h2>
<p>First after</p> <!-- matched by h2 ~ p -->
<blockquote>Quote</blockquote>
<p>Second after</p> <!-- matched by h2 ~ p -->
<p>Third after</p> <!-- matched by h2 ~ p -->
</div>
Adjacent vs General Sibling
| Combinator | Syntax | Matches |
|---|---|---|
| Adjacent | A + B |
Only the immediately next sibling |
| General | A ~ B |
All following siblings of type B |
Creative Uses
CSS-only toggle patterns:
/* Show content when a checkbox is checked */
input[type="checkbox"]:checked ~ .content {
display: block;
}
Styling siblings based on state:
/* Dim all items after a highlighted one */
.highlighted ~ .item {
opacity: 0.5;
}
Limitations
- Only works forward — you cannot select previous siblings in CSS
- Both elements must share the same parent
- Does not cross parent boundaries
Specificity
Sum of both parts: h2 ~ p = (0, 0, 2).
Use Case
General sibling selectors are powerful for CSS-only interactive patterns. They enable checkbox-based toggles without JavaScript, reveal content sections, and create state-dependent styling. They are also used in accordion patterns, tab interfaces built with radio inputs, and for applying styles to all content after a particular landmark element.