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

Can CSS Styles Be Applied to SVGs Embedded Using the `` Tag?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 22:16:15710browse

Can CSS Styles Be Applied to SVGs Embedded Using the `` Tag?

Applying CSS Styles to Embedded SVGs

When including an SVG directly into a document using the tag, styling it via the document's stylesheet is possible. However, the question arises: can similar styling be applied to SVGs embedded using the tag?

Short Answer: No

CSS styles cannot cross document boundaries, including those between the main document and the embedded SVG.

Alternative Solutions

Since an tag is involved, you can insert a stylesheet into the SVG document using JavaScript. Here's an example (assuming the has fully loaded):

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!

Statement:
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