Linking to CSS in an SVG embedded by an IMG tag

I have a page, that includes several SVG files. To synchronize the styling of those SVG files I wanted to create a single stylesheet to hold all styling information.

However, when including the SVG like below, the CSS wont get applied. Anybody having a solution to this or is it just not possible to link to other (CSS) files in an SVG referenced by <img src="..." />?

See the example code below. When loading pic.svg directly in the browser, all styles get applied and one can see a green rectangle. But when opening page.htm all there is to see is a black rectangle. So obviously none of the defined styles was applied.

page.htm

<!DOCTYPE html>
<html>
<body>
    <img src="pic.svg" style="width: 100px; height: 100px;" />
</body>
</html>

pic.svg

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<?xml-stylesheet type="text/css" href="styles.css" ?>
<svg version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 100 100"
    >
    <rect x="10" y="10" width="80" height="80" />
</svg>

styles.css

rect { 
    stroke: black;
    fill: green;
}

EDIT

From an answer, that for a short time appeared here, I got this link to the spec and the following citation. In my opinion this states, that the above code should work!

Stand-alone SVG document embedded in an HTML or XML document with the ‘img’, ‘object’ (HTML) or ‘image’ (SVG) elements

[...]

Citing from your link "Style sheets defined anywhere within the referenced SVG document (in style elements or style attributes, or in external style sheets linked with the style sheet processing instruction) apply across the entire SVG document, but do not affect the referencing document (perhaps HTML or XHTML)."


Solution 1:

An alternative is to use the <object> tag in your html :-

<object type="image/svg+xml" data="pic.svg" width="100" height="100"></object>

It's a BIG shame the <img> tag won't work. I don't want to mess about hacking with converting the SVG to a data URI. It's to do with cross-site vulnerabilities on indirectly loading resources and the use of an "Open Redirector".

Note that in my testing lastnight, the <img> tag method DOES work in IE10, but neither Chrome nor FireFox.

I don't know why <object> is allowed and <img> isn't. An oversight?

Solution 2:

For privacy reasons images must be standalone files. You can use CSS if you encode the stylesheet as a data uri. E.g.

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<?xml-stylesheet type="text/css" href="data:text/css;charset=utf-8;base64,cmVjdCB7IA0KICAgIHN0cm9rZTogYmxhY2s7DQogICAgZmlsbDogZ3JlZW47DQp9" ?>
<svg version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 100 100"
    >
    <rect x="10" y="10" width="80" height="80" />
</svg>

There are various online converters for data URIs.