Change color of svg polygon on hover

Viewed 4375

I want to change the color of each polygon of the svg on hover using css.

This is the hmtl code:

<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>

When I hover one of the polygons, its filling should turn to #000.

I've already tried to change to color using the id:

/*This does not work*/
#N:hover {
    fill: #000;
}

I found this solution using jquery, but I wonder if this can be achieved using pure css: my svg polygons fills are not changing color on hover

4 Answers

Yes because you have inlined style in your svg. You can keep it and add !important to your css

#N {
fill: #000 !important;
}

or do the following

#N{fill: #000;}
<svg class="compass-svg" width="200" height="200">
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="N" points="100,10 125,50 100,100 75,50"/>
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="NE" points="155,45 150,75 100,100 125,50"/>
</svg>

And if you want the fill to change on hover just add :hover to #N

#N:hover {
fill: #000 !important;
}

OR

#N:hover{fill: #000;}
<svg class="compass-svg" width="200" height="200">
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="N" points="100,10 125,50 100,100 75,50"/>
     <polygon fill="#fff" stroke="#000" stroke-width="1" id="NE" points="155,45 150,75 100,100 125,50"/>
</svg>

The hover isn't specific enough.

  • If you convert the element's fill to a CSS mapped property it will work.
  • Alternatively you could add !important to the hover fill.

#N:hover {
    fill: red;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" fill="#fff" style="stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>

Here is how i figured out how to do it:

This is the styling

#N:hover {
    fill: #000;
}

#NE:hover {
    fill: #000;
}

#NE {
 fill: #fff;
}
#N {
 fill: #fff;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="stroke:#000; stroke-width: 1;"/>
</svg>

when you use inline style you need to use !important

#N:hover,#NE:hover {
    fill: black!important;
}
<svg class="compass-svg" width="200" height="200">
     <polygon id="N" points="100,10 125,50 100,100 75,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
     <polygon id="NE" points="155,45 150,75 100,100 125,50" style="fill:#fff; stroke:#000; stroke-width: 1;"/>
</svg>

Related