0

I want to select previous sibling of parent using css only. How I can do it?

Here is example

<div class="a">
  A
</div>
<div class="b">
  B
   <div class="c">
     C
   </div>
</div>

Want to select class A only when class C is present.

I tried this

.a:has(+ .b:has(.c)) {
  color:red
}

but it didn't worked.

  • similar to this question [is-there-a-previous-sibling-selector](https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector) – shotgun02 Nov 01 '22 at 04:57
  • Yes I tried this. `.a:has(+ .b))` works fine for me, but I want to select the parent first, using `c` like `.b:has(.c)`, then its the previous sibling. which is not working in combinations. – bhushan laware Nov 01 '22 at 06:17
  • My requirement is to change css of `A` which is lets say breadcrum, when user is on page of class name `C` – bhushan laware Nov 01 '22 at 06:21
  • You can't nest has in that way, but there is an alternative in this case:. I'll put it in an answer. – A Haworth Nov 01 '22 at 06:27

1 Answers1

2

Nesting :has in that way is not allowed. See MDN.

However, there is an alternative in this particular scenario - you can get quite specific by requiring c to be the first child, or you can drop that and just require that b has a child class c.

With first-child requirement:

.a:has(+ .b > .c:first-child) {
  color: red;
}
<div class="a">
  A
</div>
<div class="b">
  B
  <div class="c">
    C
  </div>
</div>

and without the first-child requirement:

.a:has(+ .b > .c) {
  color: red;
}
<div class="a">
  A
</div>
<div class="b">
  B
  <div class="c">
    C
  </div>
</div>
A Haworth
  • 30,908
  • 4
  • 11
  • 14