6

TLDR;

Is it at all possible to use CSS's linear-gradient() function to fill SVG elements? Any ideas of workarounds are welcomed too.


Basically I'm trying to make a templating system for simple graphs using Mustache. The user (another developer) should be able to change the style of the graphs using CSS.

However I quickly found out that SVG's fill attribute is not happy with CSS's linear-gradient() function. fill: linear-gradient(#000, #FFF); simply makes both Chrome and Firefox complain with Invalid property value. This means that the user will have to change the SVG DOM and add a <linearGradient> element, then refer to it in fill, if said user wants any gradient effect.

This is indeed achievable within my current templating framework, but I would prefer not to change the DOM if at all possible.

Any ideas?


No, not a duplicate of SVG gradient using CSS

That question asks for any method of getting a gradient fill. This question asks specifically to use CSS's linear-gradient() function and avoid SVG's <linearGradient> element.

cyqsimon
  • 2,752
  • 2
  • 17
  • 38
  • https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Gradients – Temani Afif Aug 09 '20 at 08:27
  • 1
    @TemaniAfif Why this link? I understand one can do gradients this way - of course you can. But just like animations in SVG, there seems to be two functionally similar methods. For animations, there's SMIL and CSS animation, and you can actually use either. I'm just wondering if it's the same for gradients. – cyqsimon Aug 09 '20 at 13:37
  • no it's not the same for gradient. The only way to use CSS gradient is to consider the SVG inside a CSS mask like here: https://stackoverflow.com/a/52812880/8620333 but you have no chance with the `fill` – Temani Afif Aug 09 '20 at 13:45
  • If you only need simple gradients with a fixed number of ``s, you can change each stop color with CSS: https://stackoverflow.com/a/53725568/1869660 – Sphinxxx Aug 09 '20 at 14:20
  • 1
    I've solved this in the past by writing a conversion function that rewrites a CSS gradient function as a SVG gradient element. This enabled a (visual) editor using CSS and final rendering using SVG. - Unfortuantely I am not at large to present the code here. – ccprog Aug 09 '20 at 14:21

0 Answers0