Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclusively style parent or child when hovering over either of them?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading