How to change the color of an svg element?

You can’t change the color of an image that way. If you load SVG as an image, you can’t change how it is displayed using CSS or Javascript in the browser.

If you want to change your SVG image, you have to load it using <object><iframe> or using <svg> inline.

If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.

See :

Show code snippet

You can inline your SVG, tag your fallback image with a class name (my-svg-alternate):

<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

And in CSS use the no-svg class from Modernizr (CDN: http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js ) to check for SVG support. If there is no SVG support the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (display: none):

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}

Then you can change the color of your inlined element:

#time-3-icon {
   fill: green;
}

Leave a Comment