Styling SVG with CSS in the containing HTML
I have a SVG file containing one simple triangle named. The file is named indicator.svg:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!--Scalable Vector Graphic-->
<svg version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
baseProfile="full">
<polygon points="0,7 7,0 14,7"/>
</svg>
and I have a html with built-in CSS that tries to set the color of the SVG polygon:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.indicator{
fill:blue;
}
</style>
<title>Untitled Document</title>
</head>
<body>
<img class="indicator" src="images/indicator.svg" />
</body>
</html>
But it doesn't change the color of the triangle within the SVG to blue. How can this be fixed? I want to be able to choo开发者_Go百科se the color of the triangle from inside the HTML while the SVG itself is in a separate file.
It is quite obvious why this doesn't work for you. The fill
CSS property only applies to SVG elements, but you're trying to apply it to HTML <img>
element. The desired result can be reached other ways:
- Use true XHTML (with
application/xml
or*/*+xml
MIME type) in your main document; then, you'll be able to mix namespaces and append SVG into it. The browsers' support for this solution is pretty good; it will work in every browser supporting XHTML and SVG. - Some newer browsers (IE9+, Firefox 4+, Chrome) allow you to do the same even in HTML documents.
- Link a stylesheet into SVG document:
<?xml-stylesheet type="text/css" href="style.css"?>
. I'd personally choose this way. You won't be able to control the properties' values directly from HTML document, but you won't be required to change the SVG file. - Append the SVG file into HTML document using
<object>
and use scripting:oObjElem.contentDocument.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'polygon')[0].style.fill = 'blue';
.
精彩评论