Sibling Selector in CSS

The sibling selector ~ allows you to select all elements that come after a given element within the same parent.

Example

Let's look at 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 target all p tags that come after elements with 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 target all elements with class .elem that come after elements with 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;
}

Результат:

Practical tasks

Задание 1

Given code:

html<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li id="elem">5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
</ul>

Write a selector that selects all elements immediately after the element #elem.