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?
Here is a solution where you can add a gradient and change its colours using only CSS:
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:
Building on top of what Finesse wrote, here is a simpler way to target the svg and change it's gradient.
This is what you need to do: 1. Assign classes to each color stop defined in the gradient element. 2. Target the css and change the stop-color for each of those stops using plain classes. 3. Win!
Some benefits of using classes instead of
:nth-child
is that it'll not be affected if you reorder your stops. Also, it makes the intent of each class clear - you'll be left wondering whether you needed a blue color on the first child or the second one.I've tested it on all Chrome, Firefox and IE11:
See an editable example here: https://jsbin.com/gabuvisuhe/edit?html,css,output
Here is how to set a linearGradient on a target element: