Home >Web Front-end >CSS Tutorial >How Can I Style Embedded SVGs Using the `` Tag?

How Can I Style Embedded SVGs Using the `` Tag?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-25 17:50:14666browse

How Can I Style Embedded SVGs Using the `` Tag?

Applying Styles to Embedded SVGs

Unlike SVGs directly included via the tag, embedded SVGs using the tag cannot be styled using CSS from the document's stylesheet.

Technical Explanation

Stylesheets only apply within the boundaries of the document they are defined in. Embedded SVGs are considered separate documents, and therefore, styles defined externally cannot affect them.

Solution: Script-based Style Insertion

Since the tag provides access to the embedded SVG document, you can programmatically insert style elements into the embedded document. Here's an example:

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);

This assumes that the element has fully loaded before running the script.

Alternative Approaches

  • Include Stylesheet in SVG: Link to an external stylesheet from within the SVG file using the ?xml-stylesheet processing instruction or a element in the section.
  • Use jQuery-SVG Plugin: Utilize the jQuery-SVG plugin to apply JavaScript and CSS styles to embedded SVGs.

Direct CSS Targeting

If the embedded SVG is saved in a separate file, you can define CSS styles that target the element itself, such as:

object[data="my-embedded-svg.svg"] {
  fill: #fff;
}

This approach does not apply styles to the SVG itself, but it can be useful for adjusting the overall appearance of the embedded element.

The above is the detailed content of How Can I Style Embedded SVGs 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