Home >Web Front-end >CSS Tutorial >How Can I Effectively Style Embedded SVGs When Direct CSS Styling Is Limited?

How Can I Effectively Style Embedded SVGs When Direct CSS Styling Is Limited?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 03:16:17309browse

How Can I Effectively Style Embedded SVGs When Direct CSS Styling Is Limited?

Styling Embedded SVGs: CSS Limitations and Alternative Approaches

Overview

Styling embedded SVGs (Scalable Vector Graphics) can present challenges compared to SVGs included directly in a document. Understanding the limitations and exploring alternative methods is crucial for effective styling.

Direct CSS Styling of Embedded SVGs

When an SVG is embedded using the tag, CSS styles cannot be applied directly from the document's stylesheet. This is because CSS styles do not cross document boundaries.

object svg {
    fill: #fff;
}

Injecting Styles Using Script

Since embedded SVGs are separate documents, styles can be injected into them using script. The following method 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 }";
svgDoc.getElementById("where-to-insert").appendChild(styleElement);

Alternatively, an external stylesheet can be linked using the element:

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 Styling from SVG File

Alternatively, styles can be directly linked or included within the SVG file:

<?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>

Additional Option: jquery-svg Plugin

For further flexibility, the jquery-svg plugin provides methods to apply CSS styles and JavaScript scripts to embedded SVGs.

The above is the detailed content of How Can I Effectively Style Embedded SVGs When Direct CSS Styling Is Limited?. 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