vintorg
vintorg

Reputation: 217

How can I color fill an SVG image that is a background?

I have an SVG image as a background for an element. I need to set the color of the image, but I can't seem to figure out how to do that. My CSS code is:

.myclass {
    background-image:url(path/to/my/image) no-repeat;
    display: block;
    width: 5em;
    height: 5em;
}

Upvotes: 0

Views: 108

Answers (2)

Michael
Michael

Reputation: 7394

Did you try simply doing it in CSS? Not sure if this will work for you as I don't have a fiddle to fiddle with.

.myclass {
    background: red (path/to/my/image) no-repeat;
    display: block;
    width: 5em;
    height: 5em;
}

Upvotes: 1

TimSPQR
TimSPQR

Reputation: 2984

Ok, I have very little experience with svg, but I found this great link from SO - LINK.

I must say @Drew Baker IS THE MAN!!! I've changed his code from "look at all the svgs on a page" (.each) to just "a single one".

Here is the FIDDLE.

Hover over the dragon for a second or two the first time and you'll see the eyes turn red, like in the CSS.

JS

   var $img = $('img.svg');
   var imgID = $img.attr('id');
   var imgClass = $img.attr('class');
   var imgURL = $img.attr('src');
   $.get(imgURL, function(data) {
   var $svg = $(data).find('svg');
   $.get(imgURL, function(data) {
                                 var $svg = $(data).find('svg');
                                 if(typeof imgID !== 'undefined')
                                   {
                                    $svg = $svg.attr('id', imgID);
                                    }
                                 if(typeof imgClass !== 'undefined')
                                   {
                                    $svg = $svg.attr('class', imgClass+' replaced-svg');
                                    }
                                 $svg = $svg.removeAttr('xmlns:a');
                                 $img.replaceWith($svg);
                                 }, 'xml');
                               });       

Upvotes: 0

Related Questions