enfascination
enfascination

Reputation: 1036

Hovering over transparent SVGs

How do I get hover to work robustly with transparent SVG polygons?

In the code below, you'll see that the second triangle isn't readily recognizing :hover (and it fails completely when stroke attribute is deleted or none'd). In the third triangle, hover starts to work with transparency, but only near the text.

<html><head><style>
body { background-color: Green }
polygon:hover {
    fill:Red;
}
g:hover polygon {
    fill:Red;
}
</style></head><body>
    <svg width="300px" height="600px" viewBox="0 0 100 200" xmlns="http://www.w3.org/2000/svg" version="1.1">
        <polygon fill="white" stroke="black" stroke-width="0.5px" points="0,0 100,0 100,100 0,0" />
        <polygon fill="none" stroke="black" stroke-width="0.5px" points="0,0 0,100 100,100 0,0" />
        <g>
            <polygon fill="none" stroke="black" stroke-width="0.5px" points="0,100 100,100 100,200 0,100" />
            <text x="50" y="150" font-family="Verdana" font-size="30">hi</text>
        </g>
    </svg>
</body></html>

I've confirmed this over Chrome, Firefox, and Safari. Any ideas (that'll work across most browsers)?

Upvotes: 0

Views: 1270

Answers (2)

Holger Will
Holger Will

Reputation: 7526

Another approach is to use pointer-events="all".

With pointer-events you can control wich part of your shape reacts to pointer-events, independently of its fill or stroke.

circle:nth-of-type(1) {
  pointer-events: fill
}
circle:nth-of-type(2) {
  pointer-events: all
}
circle:nth-of-type(3) {
  pointer-events: stroke
}
circle:nth-of-type(4) {
  pointer-events: none
}
circle:hover {
  fill: red;
  stroke: blue
}
<svg width="300px" height="300px" viewBox="0 0 100 100">
  <circle cx="25" cy="25" r="20" fill="none" stroke="red" stroke-width="5" />
  <circle cx="75" cy="25" r="20" fill="none" stroke="none" stroke-width="5" />
  <circle cx="25" cy="75" r="20" fill="green" stroke="none" stroke-width="5" />
  <circle cx="75" cy="75" r="20" fill="green" stroke="red" stroke-width="5" />
</svg>

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

For each element state the fill color as fill="red", and set 0 as the fill opacity fill-opacity="0". On hover change the fill-opacity to 1:

body {
  background-color: Green
}
polygon:hover {
  fill-opacity: 1;
}
g:hover polygon {
  fill-opacity: 1;
}
<svg width="300px" height="600px" viewBox="0 0 100 200" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <polygon fill="white" stroke="black" stroke-width="0.5px" points="0,0 100,0 100,100 0,0" />
  <polygon fill="red" fill-opacity="0" stroke="black" stroke-width="0.5px" points="0,0 0,100 100,100 0,0" />
  <g>
    <polygon fill="red" fill-opacity="0" stroke="black" stroke-width="0.5px" points="0,100 100,100 100,200 0,100" />
    <text x="50" y="150" font-family="Verdana" font-size="30">hi</text>
  </g>
</svg>

Upvotes: 1

Related Questions