csscss-selectors

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


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

.check:checked ~ .content {
}

What does it mean?


Solution

  • 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;
    }
    <ol>
      <li class="b">b</li>
      <li class="a">a</li>
      <li class="x">x</li>
      <li class="b">b</li>
      <li class="b">b</li>
    </ol>

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

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