Andrii Kovalenko
Andrii Kovalenko

Reputation: 2227

Is there a way to isolate SVG styles?

<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

Answers (3)

Max
Max

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 svgs to imgs with data URLs. Simple!

Upvotes: 4

user8082874
user8082874

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

Yes, by putting the SVG in the shadowDOM of a W3C standard Web Component

supported in all modern Browsers.

Upvotes: 3

Related Questions