General sibling selector in CSS
The general sibling selector ~
selects all elements that come after
a given element within the same parent.
Syntax
selector1 ~ selector2 {
}
Example
Let's select 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 select all p tags that come
after elements with the 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 select all elements with the class
.elem that come after elements with
the 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;
}
:
See also
-
the child selector
that allows you to select elements by direct nesting -
the descendant selector,
that allows you to select an element by its parent -
the adjacent sibling selector
that allows you to select an element by its sibling -
the universal selector
that allows you to select all elements