1

I have some very simple HTML that looks like

<div id="parent">
    <a href='#link' id="child">Child</a>
</div>

I want to style the parent when hovering over the parent and I want to style the child when hovering over the child. I never want both to be styled at the same time.

I tried various combinations of :hover and :not() selectors in SCSS. Googling didn't bring me far; most solutions I found just tell me how to style the parent when hovering over the child, which is the opposite of what I want.

I found this and this workaround, both from 2013, but I was wondering whether there is a better, more modern way to do this.

1 Answers1

0

If you only intend to support modern, evergreen browsers that support :has, then you can style #parent based on the following conditions:

  • is hovered
  • does not have a hovered child

That translates to a selector of such: #parent:hover:not(:has(#child:hover)).

In the example below, the #parent is red only when it is hovered and not its child:

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

#child:hover {
  background: green;
} 
<div id="parent">
  <a href='#link' id="child">Child</a>
</div>
Terry
  • 63,248
  • 15
  • 96
  • 118
  • The project I am working on is meant to be used exclusively by myself and my friends, I know the entire target demographic by name. Modern browser requirement is not an issue for my use case. Works as intended, many thanks! – Simon Maurer Jan 14 '23 at 15:38
  • @SimonMaurer Do note that Firefox still requires a flag to be toggled for `:has` support, but otherwise all modern browsers based off Chromium or Webkit supports it already :) – Terry Jan 14 '23 at 16:01