ngplayground ngplayground - 5 months ago 559
CSS Question

img src SVG changing the fill color


<img src="logo.svg" alt="Logo" class="logo-img">


.logo-img path {
fill: #000;

The above svg loads and is natively
fill: #fff
but when I use the above
to try change it to black it doesn't change, this is my first time playing with SVG and I am not sure why it's not working.



You need to make the SVG to be an inline SVG. You can make use of this script, by adding a class svg to the image:

 * Replace all SVG images with inline SVG
    var $img = jQuery(this);
    var imgID = $img.attr('id');
    var imgClass = $img.attr('class');
    var imgURL = $img.attr('src');

    jQuery.get(imgURL, function(data) {
        // Get the SVG tag, ignore the rest
        var $svg = jQuery(data).find('svg');

        // Add replaced image's ID to the new SVG
        if(typeof imgID !== 'undefined') {
            $svg = $svg.attr('id', imgID);
        // Add replaced image's classes to the new SVG
        if(typeof imgClass !== 'undefined') {
            $svg = $svg.attr('class', imgClass+' replaced-svg');

        // Remove any invalid XML tags as per
        $svg = $svg.removeAttr('xmlns:a');

        // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
        if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
            $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))

        // Replace image with new SVG

    }, 'xml');


And then, now if you do:

.logo-img path {
  fill: #000;

Or may be:

.logo-img path {
  background-color: #000;

This works!


Credits for the above script: How to change color of SVG image using CSS (jQuery SVG image replacement)?