Home > Software engineering >  element blocks hover effect of other elements
element blocks hover effect of other elements

Time:11-30

I have two elements, a circle and a square (2 different div). The square is on top of the circle, but it blocks the hover effect of the element underneath (the circle turns blue, for example). Applying the hover effect to the square doesn't work, because the hover effect applies to every part of the circle.

In the real example (see second image), you can see that the circle is divided with the skew and rotate transformation.

I don't want to use JavaScript, just CSS and HTML.


I simplified the problem in this CodePen: codepen.io/tuurtie/pen/XWYPWEb.
enter image description here
This is an image of the actual result (red is what blocks the hover effect of the circle): enter image description here

I have played around with the overflow of both, and I have tried to make a hole in the square, but this still blocks the hover. I know I'm close!

I also added a hover effect to the red square itself, but then the hover effect doesn't work (the hover effect applies to every part of the circle).

CodePudding user response:

As @IT goldman said, you could use pointer-events: none;:

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 50%;
  top: 50%;
}

.circle {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 250px;
  height: 250px;
}

.circle:hover {
  background-color: blue;
}

.square {
  pointer-events: none;
  position: absolute;
  background-color: red;
  width: 50px;
  height: 50px;
}
<p>The hover effect of the black circle doesn't work when you go over the red square.</p>
<div >
  <div ></div>
  <div ></div>
</div>

However, this will disable any pointer events you want to apply to the square. Another solution could use a bit of JavaScript:

const circle = document.querySelector(".circle");
const square = document.querySelector(".square");

square.addEventListener("mouseover", (e) => {
  circle.classList.add("circle-on-hover");
})

square.addEventListener("mouseout", (e) => {
  circle.classList.remove("circle-on-hover");
})
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 50%;
  top: 50%;
}

.circle {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 250px;
  height: 250px;
}


/*            
  • Related