Chad Chad - 1 year ago 274
CSS Question

CSS sibling selectors (select all siblings)

Usually, I'm good with CSS, but I can't seem to figure this one out. If I have a structure of

<h2 class="open">1</h2>

how can I target all of the sibling h2s using the
class with CSS? My main issue is that sibling selectors (
.open + h2
) will only target the h2 immediately following

Answer Source

You can select all the following siblings using CSS3's ~ instead of + (which is in CSS2):

.open ~ h2

If you need to select all h2 elements that aren't .open whether they precede or follow .open, there is no sibling combinator for that. You'll need to use :not() instead:


Optionally with a child combinator if you need to limit the selection to div containers:

div > h2:not(.open)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download