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:
<div>
<h2>text</h2>
<p>
+++
</p>
<p>
+++
</p>
<p>
+++
</p>
</div>
<p>
-
</p>
h2 ~ p {
color: red;
}
:
Example
Let's target all p tags that come after elements with class .test and color them red:
<div>
<p class="test">
text
</p>
<p>
+++
</p>
<p>
+++
</p>
</div>
<p>
---
</p>
.test ~ p {
color: red;
}
:
Example
Let's target all elements with class .elem that come after elements with class .test and color them red:
<div>
<p class="test">
text
</p>
<p class="elem">
+++
</p>
<p>
---
</p>
<p class="elem">
+++
</p>
</div>
<p>
---
</p>
.test ~ .elem {
color: red;
}
:
Practical tasks
Given code:
<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.