When an SVG is directly included in a document using the <svg>
tag, you can apply CSS styles to the SVG via the document's stylesheet. However, I am trying to apply a style to an SVG which is embedded (using the <object>
tag).
Is it possible to use anything such as the following code?
object svg { fill: #fff; }
The SVG <style> element allows style sheets to be embedded directly within SVG content.
If you want to keep your SVG in files, the CSS needs to be defined inside of the SVG file. You could use a tool on the server side to update the style tag depending on the active style. In ruby you could achieve this with Nokogiri. SVG is just XML.
Edit your SVG file, add fill="currentColor" to svg tag and make sure to remove any other fill property from the file. Note that currentColor is a keyword (not a fixed color in use). After that, you can change the color using CSS, by setting the color property of the element or from it's parent.
Short answer: no, since styles don't apply across document boundaries.
However, since you have an <object>
tag you can insert the stylesheet into the svg document using script.
Something like this, and note that this code assumes that the <object>
has loaded fully:
var svgDoc = yourObjectElement.contentDocument; var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style"); styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here svgDoc.getElementById("where-to-insert").appendChild(styleElement);
It's also possible to insert a <link>
element to reference an external stylesheet:
var svgDoc = yourObjectElement.contentDocument; var linkElm = svgDoc.createElementNS("http://www.w3.org/1999/xhtml", "link"); linkElm.setAttribute("href", "my-style.css"); linkElm.setAttribute("type", "text/css"); linkElm.setAttribute("rel", "stylesheet"); svgDoc.getElementById("where-to-insert").appendChild(linkElm);
Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = "@import url(my-style.css)"
.
Of course you can directly link to the stylesheet from the svg file too, without doing any scripting. Either of the following should work:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="my-style.css" type="text/css"?> <svg xmlns="http://www.w3.org/2000/svg"> ... rest of document here ... </svg>
or:
<svg xmlns="http://www.w3.org/2000/svg"> <defs> <link href="my-style.css" type="text/css" rel="stylesheet" xmlns="http://www.w3.org/1999/xhtml"/> </defs> ... rest of document here ... </svg>
Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.
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