Home >Web Front-end >CSS Tutorial >Can CSS Styles Be Applied to SVGs Embedded within an `` Tag?
CSS Styling of Embedded SVGs
Applying CSS styles to an SVG directly included in a document using the
Short Answer: No
CSS styles do not traverse document boundaries. An
Alternative Approaches
Fortunately, there are alternative methods to style embedded SVGs:
1. Programmatic Stylesheet Insertion:
Using JavaScript, the stylesheet can be inserted directly into the SVG document within the
var svgDoc = yourObjectElement.contentDocument; var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style"); styleElement.textContent = "svg { fill: #fff }"; // Adjust as needed svgDoc.getElementById("where-to-insert").appendChild(styleElement);
2. External Stylesheet Referencing:
A element can be inserted 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);
3. CSS Import (@import Rule):
The first method can be used to insert a style element and subsequently add an @import rule:
styleElement.textContent = "@import url(my-style.css)";
4. Direct SVG Stylesheet Linking:
The SVG file itself can directly reference a stylesheet:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="my-style.css" type="text/css"?> <svg xmlns="http://www.w3.org/2000/svg"> ... (SVG content) ... </svg>
5. jquery-svg Plugin:
The jquery-svg plugin provides an alternative approach to applying JavaScript and CSS styles to embedded SVGs.
The above is the detailed content of Can CSS Styles Be Applied to SVGs Embedded within an `` Tag?. For more information, please follow other related articles on the PHP Chinese website!