Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as an "all inclusive sibling" CSS selector?

My HTML:

<p>Doggies</p> <p class="green_guys">Froggies</p> <p>Cupcakes</p> <p>Piggies</p> 

An all inclusive sibling selector (as I wish it to be), when used to select green_guys' siblings, would select the doggies cupcakes and piggies.

Other Selectors:

The + selector (a.k.a. adjacent sibling selector) would only select the cupcakes:

.green_guys + p {     /* selects the <p> element that immediately follows .green_guys */ } 

The ~ selector (a.k.a. general sibling selector) would only select the cupcakes, and piggies:

.green_guys ~ p {     /* selects all <p> elements that follow .green_guys */ } 
like image 265
Web_Designer Avatar asked Dec 08 '11 04:12

Web_Designer


People also ask

How do you select all sibling elements in CSS?

CSS All Next Siblings Selector - CSS ~ Sign Selector CSS all next siblings selector matches all element they are siblings of specified element. This Selector identify by ~ (tilde sign) between two selector element. All next siblings selected match all elements whose are sibling of specified element.

Is there a previous sibling selector?

No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2. 1.

How do I target a second sibling in CSS?

You use the general sibling selector (~) in combination with :hover . The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.


1 Answers

There is no sibling combinator that looks backward or around, only the adjacent and general sibling combinators that look forward.

The best you can do is determine a way to limit selection only to these p elements with the same parent, and then select the p children that are :not(.green_guys). If the parent element has an ID of #parent, for example, you can use this selector:

#parent > p:not(.green_guys) {     /* selects all <p> children of #parent that are not .green_guys */ } 

However the above will still match your p elements even if none of them have the class. It is currently not possible to select the siblings of an element only given the existence of said element (which is the purpose of a sibling combinator — to establish a relationship between two sibling elements).


Selectors 4's :has() will hopefully rectify this without the need for a preceding-sibling combinator, resulting in the following solution:

p:has(~ .green_guys), .green_guys ~ p {     /* selects all <p> elements that are siblings of .green_guys */ } 

This will not match anything if none of the children of the parent element have the class.

like image 136
BoltClock Avatar answered Sep 28 '22 10:09

BoltClock