David Alsbright David Alsbright - 1 year ago 119
CSS Question

Transition the fill property on an SVG image group when hovered

I'm including an SVG image file on my page within an

tag, like this:

<object type="image/svg+xml" data="linkto/image.svg">
<!-- fallback image in CSS -->

The image in question is of a world map, i want to transition the
property when the mouse hovers over a
, in this case I've grouped my SVG by continent, so South America looks something like this:

<g id="south_america">
<path fill="#FAFAFA" d="(edited for brevity)"/>

I can get the
property to change on hover by using the following CSS at the top of my SVG document:

#south_america path {
transition: fill .4s ease;
#south_america:hover path {

But I can't get the
colour to fade in with a CSS transition, the colour just changes instantly, can anyone shed light on this please?

Answer Source

In order to transition/fade, CSS needs a starting value and an ending value.
Because you set the color for the path using the SVG attribute fill="#FAFAFA", CSS doesn't process it and the transition doesn't fade.

Instead if you use CSS to set the color, the transition will behave as expected

So all I had to do to make the transition work is give the #europe a starting fill to transition from.

 path { transition: fill .4s ease; }
 /* set fill for before and for during hover */
 #europe       path { fill: red; }
 #europe:hover path { fill: white; }

Here's a working JSFiddle.

Or, doing it inline can be more convenient (style=""):

<path style="fill: #FAFAFA;" d="..."/>

Just in order for CSS to do your fading, it needs to handle the start and end values in CSS/inline style (as opposed to using the SVG fill= attribute).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download