How to animate the fill color of SVG with CSS?

Viewed 23744

CSS allows to change the color of SVG like this

.clr {fill: green;}

But when I apply animation with the same fill attributes nothing seems to work. What should I do?

<svg width="800" height="600" style="background-color:lightblue">

<circle class="clr" cx="610" cy="240" r="4" fill="gold" />

<style>

.clr {animation: col 3s linear infinite;}

@keyframes col {
0%,71% {fill:none}
72% {fill:black}
75%,100% {fill:none}
}

</style>
</svg>
4 Answers

You cannot animate from none (nothing) to green (something) for a smooth transition. Instead do:

@keyframes col {
  0%, 71% { fill: none; } /* change attribute value to `inherit` */
  72% { fill: black; }
  75%, 100% { fill: none; } /* or change value to `currentcolor` */
}

Resulting in the following:

@keyframes col {
  0%, 71% { fill: inherit; }
  72% { fill: black; }
  75%, 100% { fill: currentcolor; }
}

Then play around with the animation attribute or element.animate to achieve desired effect.

Following is the example from @Muhammad (because it is easier to see than the OP's example of a small dot in the lower right) of an svg with an inline style section. As I read the specification, it should work as is. However, browser support still seems to be lacking 3 years later, now in 2020.

SVG 2 Requirement: Add HTML5 ‘style’ element attributes to SVG's ‘style’ element.

Resolution: SVG 2 ‘style’ element shall be aligned with the HTML5 ‘style’ element.

Purpose: To not surprise authors with different behavior for the ‘style’ element in HTML and SVG content.

I have used VS Code with a plugin called jock.svg and the animation works as expected in the live preview pane. Just copy and save the svg code "as is" with a file extension of "svg".

It is hard to know what animation the OP was going for without a description because the code snippet is said to be not working.

For clarity I will describe what this example does: It displays a briefly (3% of the time) flashing black circle on a light blue background in the top left corner. Note that the original "gold" fill is ignored when the animation is working. Today in Safari (Mac, iPad), Chrome (iPad) and Edge (iPad), all I see is the "gold" circle. No animation is applied. Please comment if (when) your browser works. I suspect this hole in browser support will be filled in the future.

[Edit] It works in Chrome 81.0.4044.92 (Mac)

<svg width="800" height="600" style="background-color:lightblue">
    <circle class="color" cx="50" cy="50" r="30" fill="gold" />
    <style>
        .color {animation: col 3s linear infinite;}

        @keyframes col {
            0%,71% {fill:none}
            72% {fill:black}
            75%,100% {fill:none}
        }
    </style>
</svg>

Related