Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS sibling selectors (select all siblings) [duplicate]

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

<div>     <h2 class="open">1</h2>     <h2>2</h2>     <h2>3</h2>     <h2>4</h2>     <h2>5</h2> </div> 

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

like image 277
Chad Avatar asked Aug 05 '12 02:08

Chad


People also ask

How do you select all sibling elements in CSS?

General Sibling Selector (~) The general sibling selector selects all elements that are next siblings of a specified element.

Which of the following selectors select all siblings?

The ("element ~ siblings") selector selects sibling elements that appear after the specified "element".

Is used to select all the siblings of an element?

To select all sibling elements of an element, we will use siblings() method. The siblings() method is used to find all sibling elements of the selected element. The siblings are those having the same parent element in DOM Tree.

What is the difference between '+' and '~' sibling selectors?

2 Answers. Show activity on this post. + will only select the first element that is immediately preceded by the former selector. ~ selector all the sibling preceded by the former selector.


1 Answers

You can select all the following siblings using ~ instead of +:

.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:

h2:not(.open) 

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

div > h2:not(.open) 
like image 148
BoltClock Avatar answered Nov 01 '22 16:11

BoltClock