3

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?

Turnip
  • 35,836
  • 15
  • 89
  • 111
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
  • 2
    There is no "previous sibling" selector in CSS, so probably not – Explosion Pills May 08 '13 at 22:15
  • Would you consider making the element-to-find have an active class as well? – ntgCleaner May 08 '13 at 22:17
  • 2
    If element to find is after `#box2`, you can achieve it. The previous sibling selector, as it has been mentioned, doesn't exists (yet!): http://stackoverflow.com/questions/1817792/css-previous-sibling-selector – Pigueiras May 08 '13 at 22:23

2 Answers2

6

There were multiple proposals to CSSWG in www-style@w3.org 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.

Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52
2

Without knowing any more of your selectors, you could potentially use CSS's :not() selector.

div:not(#box1), div:not(#box2) {
    /*some style here*/
}

I would just suggest giving your #element-to-find a class as well when you select box2 and have a style ready for it.

ntgCleaner
  • 5,865
  • 9
  • 48
  • 86