What does the CSS Tilde (~) Selector Mean

Description of the tilde selector

In CSS, the tilde symbol is known as subsequent-sibling combinator, which separates two compound selectors. The elements that are represented by the two compound selectors have the same parent element. The first selector precedes (but not necessarily immediately) the element that is represented by the second selector. In other words, the subsequent-sibling combinator selects all sibling elements of a specified element.

Example of using the subsequent-sibling combinator:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .line ~ .bg-green {
        background-color: #4fe878;
      }
    </style>
  </head>
  <body>
    <ul>
      <li class="bg-green">First line</li>
      <li class="line">Second line</li>
      <li>Third line</li>
      <li class="bg-green">Fourth line</li>
      <li class="bg-green">Fifth line</li>
    </ul>
  </body>
</html>

Result

  • First line
  • Second line
  • Third line
  • Fourth line
  • Fifth line

In our next example, we select all the sibling <p> elements with the subsequent-sibling combinator. Here, the second and fourth paragraphs are selected as they are siblings. Since the third paragraph is placed within another <div>, it is not selected (as it has a different parent element).

Example of selecting <p> elements with the subsequent-sibling combinator:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p~p {
        color: #1b09de;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <p>1st paragraph</p>
      <p>2nd paragraph</p>
      <h1>First heading</h1>
      <div>
        <p>3rd paragraph</p>
      </div>
      <p>4th paragraph</p>
      <h2>Second heading</h2>
    </div>
  </body>
</html>