Home > other >  CSS selector for parent previous sibling
CSS selector for parent previous sibling

Time:11-01

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

Here is example

<div >
  A
</div>
<div >
  B
   <div >
     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.

CodePudding user response:

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 >
  A
</div>
<div >
  B
  <div >
    C
  </div>
</div>

and without the first-child requirement:

.a:has(  .b > .c) {
  color: red;
}
<div >
  A
</div>
<div >
  B
  <div >
    C
  </div>
</div>

  • Related