0

Is there a way to select elements with CSS based on whether class A or class B precedes the element first? For example:

<parent>
<div> 1 </div>
<div class='A'></div>
<div> 2 </div>
<div class='B'></div>
<div> 3 </div>
<div> 4 </div>
<div class='A'></div>
<div> 5 </div>
</parent>

Is there a way to apply a style to divs 2 and 5 (divs preceded by class A before class B)

and another style to divs 3 and 4 (divs preceded by class B before class A)

?

I tried using the selectors .A ~ * and .B ~ * which almost works, but doesn't correctly apply to situations like div 5.

  • Is it not possible to give those elements their own classes and handle their CSS through that class? – Geshode Dec 26 '22 at 00:49
  • @Geshode unfortunately no. im not actually building something from scratch. I'm adding a stylesheet into another application whose html or classes I cannot manipulate, only add a style sheet onto. – Elliot Lee Dec 26 '22 at 00:52
  • If you can inject JS, you can write JS code to class names to target those particular divs, and then style them with CSS. – kmoser Dec 26 '22 at 00:53

1 Answers1

0

You can use the :has relational Pseudo-class to query for elements that has an upcoming .A sibling.

.A ~ div {
  color: red;
}

.B ~ div:has(~ .A)  {
  color: green;
}
<div> 1 </div>
<div class='A'></div>
<div> 2 </div>
<div class='B'></div>
<div> 3 </div>
<div> 4 </div>
<div class='A'></div>
<div> 5 </div>

See https://developer.mozilla.org/en-US/docs/Web/CSS/:has#browser_compatibility for browser compatibility.

Nora Söderlund
  • 1,148
  • 2
  • 18
  • `:has` is [not currently supported on Firefox](https://caniuse.com/?search=%3Ahas), but must be enabled manually. – kmoser Dec 26 '22 at 16:42
  • Yes, as such, I linked the MDN browser compability chart, if the question is refered to in the future and current - one can see the active browser compability. Is there any clarification you propose for the answer, @kmoser? :) – Nora Söderlund Dec 26 '22 at 16:47
  • I don't have a CSS solution, just a JS one. – kmoser Dec 26 '22 at 18:03