Hideto
Hideto

Reputation: 309

How to gradient fill an SVG from an external stylesheet?

I love external stylesheets and want to be able to style any SVG graphics via an external sheet. I can declare single colour stroke and fill for my SVG logo but I want a gradient fill. I've tried a view things but can't get it to work right. Can someone help me figure out how to make it work?

I'm not sure how to put a code snippet considering I'm discussing external code, not inline, so here's a link to the SVG logo in question and its matching external stylesheet.

Actual logo I'm trying to recreate in SVG (PNG):

Cafe Logo

SVG logo: http://www.cafenocturne.com/testpage/images/svg/CafeLogoSVG.svg

Stylesheet: http://www.cafenocturne.com/testpage/css/CafeLogoSVG.css

There are some commented-out notes to make sure I don't lose the gradient code I'm trying to implement so I apologize that the CSS file is a mess. Once I can get it to work right, I won't need to keep notes there.

So how do I achieve this?

Upvotes: 0

Views: 10805

Answers (1)

Holger Will
Holger Will

Reputation: 7526

add the gradient to your SVG file, and change the stop-color from CSS:

#color1 {
  stop-color: red
}
#color2 {
  stop-color: blue
}
<svg>
  <linearGradient id="lg">
    <stop id="color1" offset="0" />
    <stop id="color2" offset="1" />
  </linearGradient>
  <circle cx="50" cy="50" r="45" fill="url(#lg)" />
</svg>

if you need more control of your gradients, you could specify gradients in a seperate file (say 'myGradients.svg')

<svg xmlns="http://www.w3.org/2000/svg">
  <linearGradient id="g1">
    <stop offset="0" stop-color="red"/>
    <stop offset="1" stop-color="blue"/>
  </linearGradient>
  <linearGradient id="g2">
    <stop offset="0" stop-color="green"/>
    <stop offset="1" stop-color="yellow"/>
  </linearGradient>
</svg>    

now in your css you can do

.logo {fill: url('myGradients.svg#g2');}

unfortunately this doesn't work in chrome :-(

alternatively you can have a copy of your gradient collection in your logo file or html, and still style it with css

.color1 {
  stop-color: green
}
.color2 {
  stop-color: yellow
}
#logo1 {
  fill: url(#g1)
}
#logo2 {
  fill: url(#g2)
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="0" height="0">
  <linearGradient id="g1">
    <stop offset="0" class="color1" />
    <stop offset="1" class="color2" />
  </linearGradient>
  <radialGradient id="g2">
    <stop offset="0" class="color1" />
    <stop offset="1" class="color2" />
  </radialGradient>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <circle id="logo1" cx="50" cy="50" r="45" />
</svg>

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <circle id="logo2" cx="50" cy="50" r="45" />
</svg>

Upvotes: 5

Related Questions