Linear gradient in SVG symbol

Viewed 3623

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>
2 Answers

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.

As pointed out in the comments, place the linearGradient outside the symbol.

Here is a modified example that works:

<svg style="visibility:hidden; width: 0; height: 0;">
  <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>
    <symbol id="symbol1" viewBox="0 0 550 90" width="100%" height="100%">
      <g fill="url(#gradient)">
        <rect x="0" y="0" width="100" height="15"/> 
        <rect x="10" y="25" width="130" height="15" />                              
      </g>
    </symbol>
  </defs> 
</svg>


<svg width="400" height="400">
  <use xlink:href="#symbol1"></use>
</svg>

Related