Reputation: 2227
<svg>
<defs>
<style>
.test {
fill: red;
}
</style>
</defs>
<circle class="test"></circle>
</svg>
<div class="test">test</div>
How to make works class .test
only for SVG element.
Is there a way to isolate SVG classes/styles?
Upvotes: 1
Views: 1891
Reputation: 2859
The shadowDOM
approach broke styles within the SVG for me. So here's an alternative:
let svgs = document.getElementsByTagName("svg");
for (let i = 0; i < svgs.length; i++) {
let svg = svgs[i];
let img = document.createElement("IMG");
img.src = `data:image/svg+xml,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
svg.parentNode.replaceChild(img, svg);
}
It converts svg
s to img
s with data URLs. Simple!
Upvotes: 4
Reputation:
You could also just do:
<svg class="MY-SVG-CLASS" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 303.182 218.285">
<defs><style>svg.MY-SVG-CLASS .cls-1{ …
Add a class to the svg and add the class to the inline style of the svg itself.
Upvotes: 0
Reputation: 21173
Yes, by putting the SVG in the shadowDOM of a W3C standard Web Component
supported in all modern Browsers.
Upvotes: 3