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 have child div not trigger hover effect of parent div?

I am trying to find out how to have a child element that has position: absolute that is positioned outside of its parent element that does not trigger the parent’s :hover effect.

Since the parent has a hover effect, the child elements will trigger the parent element, even though that child is outside of the parent element’s boundary.

Is there an attribute I am missing, or is this just the way inheritance in HTML works?

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

Picture Example:

In this image, my mouse cursor is inside the child div, but outside of the parent div.

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

.container {
  background-color: black;
  width: 800px;
  aspect-ratio: 1 / 1;
}

.container:hover {
  background-color: darkorange;
}

.child {
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
  transform: translate(-50px, 0px);
}
<div class="container">
  <div class="child"></div>
</div>

>Solution :

You can use following solutions for this.

  1. You can use pointer-events: none on the child element. But remember that this will block all types of pointer events on that, and not just hover event. So any sort of click events will also not work on that child element.

  2. Another option is to use :has() method in the css. :has() allows you to target an element that meets the conditions passed to it. You can do it like this –

  .container:not(:has(.child:hover)):hover {
    background-color: darkorange;
  }
        

This will prevent the hover effect on container when hovered over its child element, which is specified in the :has() method.
Here is the JSFiddle example demonstrating this method.
Read more about :has() in here

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