I have a svg sprite with <symbol> trhat contains a <linearGradient>. I am filing a <g> in this same <symbol> with this gradient by fill="url(#id)". However, when I load the <symbol> with <use> in other document, the <linearGradient> does not load. I can see the fill's url is referring to an absolute route instead of inside the document and not load correctly.
How can I load a <linearGradient> in a <symbol>?
<symbol viewBox="0 0 550 90" width="100%" height="100%">
<defs>
<linearGradient id="gradient">
<stop offset="-1.04974" stop-color="#D8D8D8">
<animate attributeName="offset" values="-2; 1" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.549739" stop-color="#EEEEEE">
<animate attributeName="offset" values="-1.5; 1.5" dur="1s" repeatCount="indefinite"></animate>
</stop>
<stop offset="-0.0497395" stop-color="#D8D8D8">
<animate attributeName="offset" values="-1; 2" dur="1s" repeatCount="indefinite"></animate>
</stop>
</linearGradient>
</defs>
<g fill="url(#gradient)">
<rect x="0" y="0" width="100" height="15"/>
<rect x="10" y="25" width="130" height="15" />
</g>
</symbol>
To use a gradient, we have to reference it from an object's fill or stroke attributes. This is done the same way you reference elements in CSS, using a url . In this case, the url is just a reference to our gradient, which I've given the creative ID, "Gradient". To attach it, set the fill to url(#Gradient) , and voila!
SVG provides for two types of gradients: linear gradients and radial gradients. Once defined, gradients are then referenced using 'fill' or 'stroke' properties on a given graphics element to indicate that the given element shall be filled or stroked with the referenced gradient.
The x1, x2, y1,y2 attributes of the <linearGradient> tag define the start and end position of the gradient. The color range for a gradient can be composed of two or more colors. Each color is specified with a <stop> tag. The offset attribute is used to define where the gradient color begin and end.
For me, I had display: none on my <svg> tag that contained my <defs> and <symbols>.
Make sure that initial svg does not have display:none set - use height: 0; width: 0; position: absolute; visibility: hidden instead.
Also as noted in Waruyama's answer, make sure the <defs> are outside of the <symbol> tag.
Found this hint here.
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