Mobile app version of vmapp.org
Login or Join
Alves908

: How to style an svg using external stylesheet? I have an SVG file and I want to include it in an HTML page. I want to style it using an external CSS file, but I don't want to include

@Alves908

Posted in: #Css #Html #Svg

I have an SVG file and I want to include it in an HTML page. I want to style it using an external CSS file, but I don't want to include the stylesheet reference in the SVG itself.

Is this possible? Then how would you accomplish this?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Alves908

1 Comments

Sorted by latest first Latest Oldest Best

 

@Goswami781

As already answered in this SO question, it is possible to style an SVG only if it's part of your DOM. If you load it using e.g. an <img> tag, as a background or so, only CSS code which is direct in your SVG-File would have effect.

Like described in the question's first answer this MDN article illustrates how you can use inline SVG.

However, if you want your SVG to stay in an external ressource, and not have to copy&paste it in your template, every time it changes (I hope you didn't think about this kind of 'solution'), you could load it dynamically into your DOM with a simple (untested) AJAX call:

//Assuming you have jQuery available
$.ajax({
url: './mysvgFile.svg',
success: function(data) {
if (data.childNodes.length > 0) { //should be one, _could_ be more
$('.myDiv').append(data.childNodes[0]);
} else {
console.log('invalid SVG');
}
},
error: function(data) {
console.error('Error loading SVG!');
}
});


At this point your stylesheets can manipulate elements in your SVG.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme