Home > Web Front-end > CSS Tutorial > Can CSS Styles Be Applied to SVGs Embedded within an `` Tag?

Can CSS Styles Be Applied to SVGs Embedded within an `` Tag?

Susan Sarandon
Release: 2024-12-21 18:37:16
Original
204 people have browsed it

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 tag is straightforward. However, if the SVG is embedded within an tag, this approach falls short. Can CSS styles be applied to an embedded SVG?

Short Answer: No

CSS styles do not traverse document boundaries. An tag, in this case, effectively creates a boundary between the containing document and the embedded SVG.

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 tag. This assumes the has fully loaded.

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);
Copy after login

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);
Copy after login

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)";
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template