Reputation: 11997
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?
Upvotes: 6
Views: 2882
Reputation: 2800
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>
Upvotes: 3
Reputation: 3761
You should use id
s to distinguish elements from each other.then configure CSS styles to affect certain elements. for browser support, its a common practice to put your CSS styles into separate files or <style>
sections.
Upvotes: 0
Reputation: 55392
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).
Upvotes: 3