Can't apply hover effect to parent

Hi guys. I will give the code below as an example. When the a tag in this code is hovered, I want the background of #parent to be blue. How can I do that?

<div id="parent">
  <a id="child">Select</a>
</div>

I think you need javascript to do it. Not sure if :hover in CSS can switch between child and parent. (unless there is a fancy way to do it with the css :before selector but it is used to insert things and you may not want to insert & style)

someone online has a possible solution (I haven’t tried)

It isn’t super well supported just yet but you can use the new :has() pseudo-class selector.

#parent:has(#child:hover) {
  background-color: red;
}

https://www.youtube.com/results?search_query=%3Ahas()

it’s like a regex lookahead I guess!

I think the implementation is pretty complex.

https://bugs.webkit.org/show_bug.cgi?id=227702
https://bugs.chromium.org/p/chromium/issues/detail?id=669058

1 Like