Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define SVG gradient in page-global CSS file

On my HTML page, I have some JavaScript code that generates SVG elements and adds them to the HTML page.

At the moment, all of the styling (fill colors etc.) for those SVGs is defined in the page’s CSS. This way the SVGs can use the same CSS classes and I need to define the properties only once.

Now I want these SVGs to use linear gradients. However, MDN doesn’t seem to reveal any way to define the linear gradient within the page-global CSS. So my questions are as follows:

  • Is there any way to define the linear gradient in the page-global CSS?
  • If not, and if I were to define the linear gradient using a <linearGradient> element within each SVG, is it OK for them to have the same ID? Will fill: url(#my-gradient) correctly access the gradient from the relevant SVG?
  • If not, how can I declare a single <linearGradient> with an ID outside of any SVG? Is it possible to have a “dummy” SVG that defines only the gradient and the CSS can refer to that gradient by its ID?
like image 275
Timwi Avatar asked Aug 17 '15 11:08

Timwi


Video Answer


1 Answers

Is there any way to define the linear gradient in the page-global CSS?

No. You can style some of the linearGradient properties with CSS, but you can't define the gradient itself.

If not, and if I were to define the linear gradient using a element within each SVG, is it OK for them to have the same ID?

If you mean more than one linearGradient with the same id, then No. id attributes must be unique.

If not, how can I declare a single with an ID outside of any SVG? Is it possible to have a “dummy” SVG that defines only the gradient and the CSS can refer to that gradient by its ID?

You can define a linearGradient in one inline SVG and access it from another. You can use CSS to assign the gradient.

svg rect {
  fill: url(#mygradient);
}

#mygradient stop.start-color {
  stop-color: red;
}

#mygradient stop.end-color {
  stop-color: blue;
}
<svg width="0" height="0">
  <defs>
    <linearGradient id="mygradient">
      <stop offset="0" class="start-color"/>
      <stop offset="1" class="end-color"/>
    </linearGradient>
  </defs>
</svg>

<svg>
  <rect width="300" height="150"/>
</svg>
like image 182
Paul LeBeau Avatar answered Sep 22 '22 01:09

Paul LeBeau