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?
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.
-
You can use
pointer-events: noneon the child element. But remember that this will block all types of pointer events on that, and not justhoverevent. So any sort of click events will also not work on that child element. -
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
