What does the "~" (tilde/squiggle/twiddle) CSS selector mean?
The tilde (~
) in CSS is the general sibling combinator, also called the “general sibling selector.” It selects all siblings of a given element that appear after it (in the DOM), at the same nesting level.
A ~ B { /* styles */ }
Here, any B
element that shares the same parent as A
and comes after A
in the HTML flow will be matched.
1. Example
<div> <p class="first">Paragraph One</p> <p class="second">Paragraph Two</p> <p class="third">Paragraph Three</p> </div>
CSS using ~
:
.first ~ p { color: red; }
- All
<p>
elements after.first
in the DOM become red. - That means
.second
and.third
paragraphs are styled red, while.first
itself is not affected.
2. Comparing the Sibling Selectors
A + B
(Adjacent Sibling Selector)
- Matches only the immediate next sibling of
A
. - Example:
Only affects.first + p { color: blue; }
.second
if it immediately follows.first
.
A ~ B
(General Sibling Selector)
- Matches all siblings of type
B
that come afterA
. - In the above example, it would match
.second
and.third
if they follow.first
.
3. Practical Use Cases
-
Styling All Subsequent Elements
If you have a layout where once a certain element appears, all following siblings need a different style, the~
selector is convenient. -
Form Validation
In forms, you could highlight or disable certain fields that come after a specific element based on a class or state. -
Thematic Break or Divider
Suppose you have an<hr class="section-end">
, and all paragraphs after that<hr>
should have a different style.
4. Limitations and Performance
-
No “Previous” Selector
The~
combinator only matches siblings after the triggering element, never before. There's no inverse to look backward in pure CSS. -
Performance Considerations
Overusing complex sibling selectors can affect rendering performance in large documents—though modern browsers are generally quite optimized.
Key Takeaway
The ~
(tilde) CSS selector is the “general sibling combinator,” selecting all following siblings of a given element on the same level. It’s useful for applying styles to elements that appear after a certain “trigger” in the DOM order.