SVG gradient using CSS

Hrishikesh Choudhari picture Hrishikesh Choudhari · Dec 27, 2012 · Viewed 117.6k times · Source

I'm trying to get a gradient applied to an SVG rect element.

Currently, I'm using the fill attribute. In my CSS file:

rect {
    cursor: pointer;
    shape-rendering: crispEdges;
    fill: #a71a2e;
}

And the rect element has the correct fill color when viewed in the browser.

However, I'd like to know if I can apply a linear gradient to this element?

Answer

Thomas W picture Thomas W · Dec 27, 2012

Just use in the CSS whatever you would use in a fill attribute. Of course, this requires that you have defined the linear gradient somewhere in your SVG.

Here is a complete example:

rect {
    cursor: pointer;
    shape-rendering: crispEdges;
    fill: url(#MyGradient);
}
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <style type="text/css">
        rect{fill:url(#MyGradient)}
      </style>
      <defs>
        <linearGradient id="MyGradient">
          <stop offset="5%" stop-color="#F60" />
          <stop offset="95%" stop-color="#FF6" />
        </linearGradient>
      </defs>
      
      <rect width="100" height="50"/>
    </svg>