Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CSS :has selector for nested elements?

How can I use the :has selector to go multiple levels deep?

I tried the following code, but it doesn't seem to be supported:

div:has(p:has(span)) {
  background: orange
}
<div>
  <p>
    <span>Hello</span>
  </p>
</div>

<div>
  <p>Bye</p>
</div>
like image 665
Shahriar Avatar asked Sep 03 '25 16:09

Shahriar


1 Answers

Assuming you only need to style the <div> if it has a descendant <p> element that in-turn has a descendant <span> element, I'd suggest:

div {
  background-color: blue;
}

div:has(p span) {
  background: orange;
}
<div>
  <p>
    <span>Hello</span>
  </p>
</div>

<div>
  <p>Bye</p>
</div>

JS Fiddle demo.

It's worth adding the caveat that this does not currently work in Firefox (version 111.0.1, running on Ubuntu 22.10). So browser variance and inconsistency is to be expected.

like image 89
David Thomas Avatar answered Sep 05 '25 08:09

David Thomas