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?
Webmasters Stack Exchange is a question and answer site for webmasters. It only takes a minute to sign up.
Sign up to join this communityI 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?
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.