Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector to get preceding sibling [duplicate]

Is there any way using pure CSS(3) to select an element that is a preceding sibling of an element with a particular class?

i.e.:

html:

<div id='element-to-find'></div>
<div id='box1'></div>
<!-- a bunch more DOM elements between here --->
<div id='box2'>
      <div id='inner-box'></div>
</div>

css:

#box1{ /*some styling*/ }
#box2{ /*some styling*/ }

#box2.active .....

Now, when #box2 has the class active I want to select and do something to the style of #element-to-find. Is there anyway to accomplish this?

like image 604
sadmicrowave Avatar asked May 14 '26 18:05

sadmicrowave


1 Answers

There were multiple proposals to CSSWG in [email protected] mailing list as for previous-sibling combinator: my one (2012), another 1, 2 (2013).

Common answer by Tab Atkins is like "we already have subject indicator for this". For selecting descendants of previous sibling (which would be trivial with previous-sibling combinator, e.g. .example - UL > LI), he suggests to use :matches() functional pseudoclass, e.g. :matches(!UL + .example) > LI. Both subject indicator and :matches() are currently in draft state and cannot be used in real world yet.

So you should add a regular class to the element-to-find element or (much less desired if your active class is added not via JS) use JavaScript to emulate previous-sibling-combinator functionality.

like image 90
Marat Tanalin Avatar answered May 18 '26 19:05

Marat Tanalin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!