I am trying to find out how to have child-divs that have position absolute that is positioned outside of the parent div NOT trigger the hover effect on parent. Since the parent has a hover effect, the child-divs still triggers the parent div eventho they are outside of the parent div boundry. Is there an attribute i am missing or is this just the way inheritance in html works?
Picture Example. (In this image, my mouse cursor is inside the child div but outside of the parent div)
<!DOCTYPE html>
<head>
<style>
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);
}
</style>
</head>
<body>
<div class="container">
<div class="child"></div>
</div>
</body>
2
Answers
You can add
pointer-event: none;
to the child element, which makes it not trigger any mouse events, including mouse hover.You can use following solutions for this.
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 justhover
event. 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 –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