How to style the parent element when hovering a child element with CSS?

Spread the love

Sometimes, we want to style the parent element when hovering a child element with CSS.

In this article, we’ll look at how to style the parent element when hovering a child element with CSS.

How to style the parent element when hovering a child element with CSS?

To style the parent element when hovering a child element with CSS, we disable pointer events on the parent.

For instance, we write

<div class="parent">
  parent - you can hover over here and it won't trigger
  <div class="child">hover over the child instead!</div>
</div>

to add nested divs.

Then we write

div.parent {
  pointer-events: none;
}

div.child {
  pointer-events: auto;
}

div.parent:hover {
  background: yellow;
}

to disable pointer events on the parent div with pointer-events: none; to stop the default hover styles from being applied to it.

Then we apply our own hover styles to the parent div with

div.parent:hover {
  background: yellow;
}

Conclusion

To style the parent element when hovering a child element with CSS, we disable pointer events on the parent.

Leave a Reply

Your email address will not be published. Required fields are marked *