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 choose the color of the triangle from inside the HTML while the SVG itself is in a separate file.
There are many Scalable Vector Graphics (SVG), but only certain attributes can be applied as CSS to SVG. Presentation attributes are used to style SVG elements and can be used as CSS properties. Some of these attributes are SVG-only while others are already shared in CSS, such as font-size or opacity .
Unfortunately you can't use a different tag such as an <iframe> because that won't work as a link so you'll have to embed the CSS in a <style> tag within the file itself. One other way to do this would be to have the SVG data within the main html file i.e.
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
The SVG <style> element allows style sheets to be embedded directly within SVG content.
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:
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.<?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.<object>
and use scripting: oObjElem.contentDocument.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'polygon')[0].style.fill = 'blue';
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With