Search code examples
csssvghoverpolygonmouse-cursor

SVG - polygon hover does not work correclty


As you can see on gif below, :hover state does not work properly when I move the mouse cursor from bottom polygon to upper polygon:

polygon {
  stroke-width: 5;
  stroke: red;
  fill: none;
}

polygon:hover {
  fill: red;
}
<svg viewBox="0 0 999 799">
  <polygon points="445,161 345,174 500,10" />
  <polygon points="445,161 345,174 500,270" />
</svg>

[jsfiddle]

enter image description here

Tested in Chrome and Firefox - the result is the same.

How can I achieve SVG polygon turn :hover state on right after mouse cursor enters its borders?


Solution

  • There is no fill to catch the pointer event so it fails.

    A simple transparent fill corrects it.

    polygon {
      stroke-width: 1;
      stroke: red;
      fill: transparent;
    }
    polygon:hover {
      fill: red;
    }
    <svg viewBox="0 0 999 799">
      <polygon points="445,161 345,174 500,10" />
    
      <polygon points="445,161 345,174 500,270" />
    </svg>

    As mentioned by Robert Longson

    pointer-events: visible is the preferred and performant solution.

    polygon {
      stroke-width: 1;
      stroke: red;
      fill: none;
      pointer-events: visible;
    }
    polygon:hover {
      fill: red;
    }
    <svg viewBox="0 0 999 799">
      <polygon points="445,161 345,174 500,10" />
    
      <polygon points="445,161 345,174 500,270" />
    </svg>