I have a web page with two or more SVG tags. Each SVG tag contains a style tag block containing the CSS styles for the given SVG element. Unfortunately, it appears that these stylesheets bleed into the global styles. For example, setting the style for class 'x1' on the first SVG element will cause the style for class 'x1' on the second SVG to be set as well. I would like to be able to set different styles for each specific SVG document. Is this possible?
Once browsers support it, you want <style scoped>
. That means Firefox 21 or later, or Chrome 19 or later (but you need to enable it in chrome://flags).
If you don't need to support IE and other ancient browsers, create a Custom Element, that will put all it's children into it's Shadow Root.
class SVGContainer extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'closed'});
shadowRoot.append(...this.childNodes);
}
}
customElements.define('svg-container', SVGContainer);
<style>#svg-text { fill: red; }</style>
<label id="html-text">I am HTML</label>
<svg-container>
<svg viewBox="0 0 100 30">
<style>#html-text { color: red; }</style>
<text id="svg-text" y="20">I am SVG</text>
</svg>
</svg-container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With