Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

html - 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)."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...