I recently had to figure out, how to create linear gradients within SVG without using PNG files or anything else. Since the way is simple and also very powerful, I like to share with you a very simple example.
Let's consider this simple SVG structure:
<svg width="220" height="120">
<g>
<rect x="10" y="10" width="200" height="100" class="rectangle" />
</g>
</svg>
That simply renders a black rectangle. I now want a left to right linear gradient as a fill color of the rectangle. We need to define this within the <defs>
tag of the SVG element.
<svg width="220" height="120">
<g>
<rect x="10" y="10" width="200" height="100" class="rectangle" />
</g>
<defs>
<linearGradient id="myGradient">
<stop offset="0%" class="start" />
<stop offset="100%" class="end" />
</linearGradient>
</defs>
</svg>
The id of the linearGradient
tag we will use as a fill reference for the rect element. stop
tags are used to define the breakpoints and color changing points for the gradient. You can define even more than just two.
The needed CSS looks like that:
.rectangle {
fill: url(#myGradient);
}
.start {
stop-color: #a0ced9;
}
.end {
stop-color: #83a9b2;
}
As you can see we just need to reference the gradient using url(#myGradient)
. This directly searches for the defined linear gradient (or different gradient). The colors for the different stop elements need to be defined by using the stop-color attribute.
Here is the result:
Post: If you want to create a linear gradient from top to bottom then you need to change the linear gradient definition to <linearGradient id="myGradient" x2="0%" y2="100%">
.
Top comments (0)