2

I want to manipulate SVG with CSS and I just learned I can add an ID to an SVG element and do this, but putting SVG in the HTML is really messy. My question is, if I load the SVG with an image tag, and add the ID into the SVG file's code, will the ID work the same way?

  • Interesting question -- I've only recently started using CSS with inline SVG (via d3.js), and it's a great way to keep color schemes consistent and flexible. I tried a few tests with external files after reading your question, with no success. According to [this question](http://stackoverflow.com/questions/18434094/how-to-style-svg-with-external-css), it's probably not possible unless you add CSS to the SVG file itself. – Michael McMullin Aug 28 '15 at 23:55
  • I did further research and found that this can be done! One must embed the svg via an `object` tag - see this tutorial: https://css-tricks.com/using-svg/ - Ill give someone else an chance to answer with this in case they might already be working on it. –  Aug 29 '15 at 00:10

1 Answers1

0

As you may or may not have realised, CSS does not work across document boundaries. So if your SVG is in a separate file, you cannot style it with CSS in your HTML. Whether it is an <img> or an <object>.

If you want to style the SVG with CSS, you have two choices:

(1) inline the SVG in the HTML, or

(2) add the CSS stylesheet to the SVG file itself. You can use a <style> element, or you can reference an external stylesheet from the SVG:

<?xml-stylesheet type="text/css" href="my_svg_styles.css" ?>

However external references like this will not work if you are embedding the SVG with <img> or background-image. There are special privacy rules that forbid it. All image files referenced from <img> have to be self-contained.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181