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:
<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?<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?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>
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