Chris W.
Chris W.

Reputation: 23280

Re-using SVG gradient via CSS

So I know I can swap out a gradient fill on an svg with css, something like;

<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <style type="text/css">
    rect{fill:url(#GradientSwap1)}
  </style>
  <defs>
    <linearGradient id="GradientSwap1">
      <stop offset="5%" stop-color="#F00" />
      <stop offset="95%" stop-color="#999" />
    </linearGradient>
  </defs>

  <rect width="100" height="50"/>
</svg>

and using ng-class I can swap out more than one of these gradients, except I can only get it to work if I include the <linearGradient> in the defs embedded into each SVG.

My question is, and what I can't seem to figure out. Is there a way to pull these gradient defs out of the SVG and make them into a resource I can use in others? Like in the .NET / XAML world, it would be really easy for me to pull them out, throw them in a resource dictionary, and use the same ones all over the place for whatever I like.

So is there an html5/css3/angular approach to the same conundrum? The idea of having to have to multiple SVG's with potentially multiple of the same Gradient defs reiterated for every single one just sounds wrong.

Upvotes: 3

Views: 650

Answers (1)

melissa.mcmurtrie
melissa.mcmurtrie

Reputation: 96

You should be able to define the gradient once and then call it in the CSS to apply anywhere. You could apply to all svgs or give it a class.

<svg>
<defs>
<linearGradient id="GradientSwap1">
  <stop offset="5%" stop-color="#F00"></stop>
  <stop offset="95%" stop-color="#999"></stop>
</linearGradient>
</defs>

<section>
<svg class="icon shape-facebook">
    <path d="M28.3,62V35.2h-5.5v-9.4h5.6v-7.7c0,0,0.3-9.8,9.8-9.8s9.5,0,9.5,0v9.2H42.1c0,0-2.699,0-2.699,2.7c0,2.7,0,5.8,0,5.8H48
l-1.1,9.4H39.6V62H28.3z"></path>
</svg>
<svg class="icon shape-heart" x="0" y="0">
        <path d="M35.645,59.413c0,0,26.949-19.601,26.949-34.12c0-16.752-22.049-22.047-26.949-1.674
    c-4.9-20.373-26.95-15.078-26.95,1.674C8.695,39.812,35.645,59.413,35.645,59.413z"></path>
</svg>

.shape-heart { fill: url('#GradientSwap1'); }

http://jsfiddle.net/v6osyy5v/1/

Upvotes: 1

Related Questions