Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS stylesheet scoped to a single svg tag

Tags:

html

css

svg

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?

like image 838
Viper Bailey Avatar asked Feb 01 '13 23:02

Viper Bailey


2 Answers

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).

like image 175
Neil Avatar answered Sep 30 '22 12:09

Neil


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>
like image 20
Alexander Shutau Avatar answered Sep 30 '22 12:09

Alexander Shutau