Viper Bailey
Viper Bailey

Reputation: 11997

CSS stylesheet scoped to a single svg tag

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

Answers (3)

Alexander Shutau
Alexander Shutau

Reputation: 2800

Use Shadow DOM

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

Ramin Omrani
Ramin Omrani

Reputation: 3761

You should use ids 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

Neil
Neil

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

Related Questions