csssvgcolors

How can I change the color of an 'svg' element?


I want to use this technique and change the SVG color, but so far I haven't been able to do so. I use this in the CSS, but my image is always black, no matter what.

My code:

.change-my-color {
  fill: green;
}
<svg>
    <image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src="ppngfallback.png" />
</svg>


Solution

  • 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:

    #time-3-icon {
       fill: green;
    }
    
    .my-svg-alternate {
      display: none;
    }
    .no-svg .my-svg-alternate {
      display: block;
      width: 100px;
      height: 100px;
      background-image: url(image.png);
    }
    <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" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206
        C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161
        C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505
        c-37.093,6.938-124.97,21.35-134.613,21.35c-13.808,0-25-11.192-25-25c0-9.832,14.79-104.675,21.618-143.081
        c0.274-1.542,1.615-2.669,3.181-2.669h0.008c1.709,0,3.164,1.243,3.431,2.932l18.933,119.904L382.816,265.785z"/>
    </svg>
    
    <image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

    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 isn't any 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;
    }