Home >Web Front-end >CSS Tutorial >How Can I Effectively Style Embedded SVGs When Direct CSS Styling Is Limited?
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.
When an SVG is embedded using the
object svg { fill: #fff; }
Since embedded SVGs are separate documents, styles can be injected into them using script. The following method assumes the
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);
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>
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!