General sibling selector in CSS

The general sibling selector ~ selects all elements that come after a given element within the same parent.

Syntax

cssselector1 ~ selector2 {
  
}

Example

Let's select all the p tags that come after the h2 tags and color them red:

html<div>
  <h2>text</h2>
  <p>
    +
  </p>
  <p>
    +
  </p>
  <p>
    +
  </p>
</div>
<p>
  -
</p>
cssh2 ~ p {
  color: red;
}

Результат:

Example

Let's select all p tags that come after elements with the class .test and color them red:

html<div>
  <p class="test">
    text
  </p>
  <p>
    +
  </p>
  <p>
    +
  </p>
</div>
<p>
  -
</p>
css.test ~ p {
  color: red;
}

Результат:

Example

Let's select all elements with the class .elem that come after elements with the class .test and color them red:

html<div>
  <p class="test">
    text
  </p>
  <p class="elem">
    +
  </p>
  <p>
    -
  </p>
  <p class="elem">
    +
  </p>
</div>
<p>
  -
</p>
css.test ~ .elem {
  color: red;
}

Результат:

See also