Mr_Green
Mr_Green

Reputation: 41832

Reusable SVG with different gradient colors

As per my requirement, I need shaped path in which I need to apply different gradient colors. Just for example here, I am taking a circle and trying to do the same.

Here is the code:

.box--blue{
  fill: blue;
}

.box--red{
  fill: red;
}
<div>
  <svg>
    <defs>
      <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0%" stop-color="transparent"/>
        <stop offset="100%" stop-color="blue"/>
      </linearGradient>
    </defs>
    <symbol id="gra2" viewbox="0 0 100 100">
  
  <circle cx="50" cy="50" r="50" fill="url(#Gradient2)" />
    </symbol>
</svg>
</div>


<div class="box box--red">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

<div class="box box--blue">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

Requirement:

I need those two gradient shapes with different colors by reusing the available SVG.

Browser support: IE10+, chrome and Firefox.

Note: I don't want to hardcode each color related gradient under the SVG. The Gradient color should be able to inherit. That is how I can reuse the SVG, IMO.

Upvotes: 3

Views: 2503

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

What you want is not possible.

The nearest I think you can get is use the special colour currentColor to pass the current value of CSS color into the symbol. You can pass it to the symbol, but not the gradient. So you would need to use it to color one circle. Then put a gradient on top of that. However, in this solution, the circle obviously can't be partially transparent as in your example.

.box--blue {
  color: blue;
}

.box--red {
  color: red;
}
<div>
  <svg>
    <defs>
      <linearGradient id="Gradient2" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0%" stop-color="white"/>
        <stop offset="100%" stop-color="transparent"/>
      </linearGradient>
    </defs>
    <symbol id="gra2" viewbox="0 0 100 100">
      <circle cx="50" cy="50" r="50" fill="currentColor" />
      <circle cx="50" cy="50" r="50" fill="url(#Gradient2)" />
    </symbol>
</svg>
</div>


<div class="box box--red">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

<div class="box box--blue">
  <svg>
    <use xlink:href="#gra2"></use>
  </svg>
</div>

Upvotes: 5

Related Questions