0

I plan to animate SVG with CSS, which is loaded inside an object element, therefore exists in its own content document, therefore the linked CSS of my HTML document does not apply there.

Luckily SVG has its own way to include CSS. You just need to put a line like this before your root <svg> element.

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

If I include this line manually and load the SVG with pure HTML inside an <object> element, then my CSS rules will be realized on the SVG.

However, I tried to automate it on the client side by loading the SVG as a text, insert the stylesheet link, create a blob from the text, finally add the URL of the blob as the data attribute of a <object> element. This displayed the image and presented the same DOM structure in the inspector as the pure HTML solution, but the CSS rules were not realized.

Even in the most simple case, when I load an SVG with JS, which already contains the stylsheet link, the rules won't be applied. Which is presented in my self-contained example on glitch.

What is the reason behind this? Is there a way to circumvent this limitation, without inserting the SVG directly inside the HTML?

atevm
  • 801
  • 1
  • 14
  • 27
  • External styles on SVG-Elements only get applied if the `SVG` is as such in the markup. Not as `object`, not as `image`, but as ``. Else you have to define the style as inline style of the SVG-Element (after the root element). Also see https://stackoverflow.com/questions/18434094/how-to-style-svg-with-external-css – Lain Jul 07 '18 at 18:09
  • @Lain Thank you for the information. However please check out my example on glitch where the external styles are applied on the SVG even if it is presented in an `object` element, at least in my browsers: Chromium v66.0.3359.181 and Firefox v59.0.2 – atevm Jul 07 '18 at 18:30
  • Yes, the example threw a 404 yesterday, now it works. According to this https://css-tricks.com/using-svg/ external styles work as long as it is defined in the object and the svg is "inline". Yours is defined as blob which I assume gets treated the same way as base64 - the markup is not there for the browser just the result. – Lain Jul 08 '18 at 06:10
  • I suggested that it behaves similarly as requesting some server resources with XHR, at least according to this source: https://www.w3.org/TR/FileAPI/#requestResponseModel – atevm Jul 08 '18 at 14:47
  • 1
    Well by requesting it by XHR one could add it as inline svg aswell. It depends how you handle the fetched XHR. Anyway, I think the baseline is that it only works properly if the browser has the unencoded markup in the DOM, which either happens by adding a svg tag to it or directly reference it as object data. – Lain Jul 08 '18 at 16:13

0 Answers0