| title | The General Sibling Combinator | ||||||
|---|---|---|---|---|---|---|---|
| description | Learn how to use the General Sibling Combinator (~) to select all elements that follow a specific preceding element, as long as they share the same parent. | ||||||
| keywords |
|
||||||
| tags |
|
||||||
| sidebar_label | General Sibling Combinator |
The General Sibling Combinator (~) is a much more flexible alternative to the strict Adjacent Sibling Combinator (+).
While the Adjacent Sibling Selector only targets the one element immediately following the first, the General Sibling Combinator targets all subsequent siblings that follow a specific preceding element, as long as they share the same parent.
The General Sibling Combinator is represented by the tilde sign (~) placed between two selectors.
preceding_selector ~ target_selector {
/* styles applied to ALL following target_selector elements */
}preceding_selector: The starting element (e.g.,.intro,h3).target_selector: The element type that is targeted if it appears later in the sequence, within the same parent.
Imagine you have an article where you want all standard paragraphs (<p>) that appear after a specific introductory paragraph (.intro) to have a unique background color.
<div class="article-body">
<p class="intro">This is the introduction paragraph.</p>
<p>First follow-up paragraph.</p>
<div>A random element doesn't break the flow.</div>
<p>Second follow-up paragraph.</p>
</div>/* Targets ALL <p> elements that follow an element with class .intro */
.intro ~ p {
background-color: #f0f4c3; /* Pale Yellow */
border-left: 5px solid #cddc39; /* Lime Green border */
padding: 10px;
}In this example, both the "First follow-up paragraph" and the "Second follow-up paragraph" are styled, even though they are separated by a <div> tag. The flow is not broken by intervening elements, only by the end of the parent container.
This is a critical distinction to master:
| Combinator | Syntax | Condition | Targets |
|---|---|---|---|
| Adjacent | A + B |
Strict: B must immediately follow A. |
Only the first following sibling. |
| General | A ~ B |
Flexible: B can follow A anywhere in the sequence. |
All following siblings of type B. |
Consider a list of items:
<li>Start</li><li>A</li><li>B</li><li>C</li>
- Rule:
li:first-child + li(Adjacent)$\rightarrow$ Styles only Item A. - Rule:
li:first-child ~ li(General)$\rightarrow$ Styles Item A, Item B, and Item C.
In this demo, the CSS rule targets all <span> elements that appear after the <h3> element within the same parent div. Notice how the intervening paragraph doesn't stop the styling.
Challenge: Try changing the CSS rule from h3 ~ span to h3 + span. You will see the styling disappear completely because the p tag is immediately following the h3, breaking the adjacent requirement.