Applying CSS Styles to Embedded SVGs
When including an SVG directly into a document using the
Short Answer: No
CSS styles cannot cross document boundaries, including those between the main document and the embedded SVG.
Alternative Solutions
Since an
var svgDoc = yourObjectElement.contentDocument; var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style"); styleElement.textContent = "svg { fill: #fff }"; // style as desired svgDoc.getElementById("where-to-insert").appendChild(styleElement);
Additionally, you can insert a element to 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);
Direct Linking
You can also link to the stylesheet directly from the SVG file, without scripting:
<?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>
Additional Option: JQuery-SVG Plugin
As of 2015, you can apply JS scripts and CSS styles to embedded SVGs using the jquery-svg plugin.
The above is the detailed content of Can CSS Styles Be Applied to SVGs Embedded Using the `` Tag?. For more information, please follow other related articles on the PHP Chinese website!