Tomasz Nocoń Tomasz Nocoń - 2 months ago 6
HTML Question

Don't apply :hover when hovering on :before element

I want to apply some styles to the :before pseudo-element when hovering the element, but not when hovering the :before element itself. Is it possible?

html:

<div class="box">Hover this to get green</div>


css:

.box {
border: 1px solid black;
}

.box:before {
border: 1px solid black;
transform: translateY(20px);
position: absolute;
color: red;
content: "Hovering this should not make it green";
}

.box:hover:before {
color: green;
}


JSFiddle

Answer

You could set pointer-events: none on pseudo element which is also going to remove hover event from it.

.box {
  border: 1px solid black;
}
.box:before {
  border: 1px solid black;
  transform: translateY(20px);
  position: absolute;
  color: red;
  content: "Hovering this should not make it green";
}
.box:hover:before {
  color: green;
}
.box:before {
  pointer-events: none;
}
<div class="box">Hover this to get green</div>

Comments