What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

CssCss Selectors

Css Problem Overview


Searching for the ~ character isn't easy. I was looking over some CSS and found this

.check:checked ~ .content {
}

What does it mean?

Css Solutions


Solution 1 - Css

The ~ selector is in fact the subsequent-sibling combinator (previously called general sibling combinator until 2017):

> The subsequent-sibling combinator is made of the "tilde" (U+007E, ~) > character that separates two sequences of simple selectors. The > elements represented by the two sequences share the same parent in the > document tree and the element represented by the first sequence > precedes (not necessarily immediately) the element represented by the > second one.

Consider the following example:

.a ~ .b {
  background-color: powderblue;
}

<ul>
  <li class="b">1st</li>
  <li class="a">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="b">5th</li>
</ul>

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

Solution 2 - Css

Good to also check the other combinators in the family and to get back to what is this specific one.

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

Example checklist:


The one we are looking at here is the General sibling combinator / Subsequent-sibling combinator

Solution 3 - Css

General sibling combinator

> The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.

More info

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTarangView Question on Stackoverflow
Solution 1 - CssSalman AView Answer on Stackoverflow
Solution 2 - CssL JView Answer on Stackoverflow
Solution 3 - CssRohit Azad MalikView Answer on Stackoverflow