SVG Linear Gradients
SVG supports rich color gradients natively. A linear gradient smoothly transitions between two or more colors along a straight line.
How Linear Gradients Work
Creating a gradient in SVG is a two-step process:
- Define the gradient inside
defsand give it anid. - Reference it on a shape's
fill(orstroke) usingurl(#yourId).
The linearGradient Element
The gradient direction is controlled by four attributes that define a vector from start to end as percentages of the SVG's width and height:
x1,y1: The start point of the gradient direction (as a percentage). Default0% 0%.x2,y2: The end point of the gradient direction. Default100% 0%(left to right).
To create a top-to-bottom gradient, use x1="0%" y1="0%" x2="0%" y2="100%".
To create a diagonal gradient, use x1="0%" y1="0%" x2="100%" y2="100%".
The stop Element
Inside the linearGradient, you define the colors at key points along the gradient vector using stop elements. Each has two key attributes:
offset: Where along the gradient this color appears (0%= start,100%= end).stop-color: The color at this point. Accepts any CSS color value.stop-opacity: Optional. The opacity of this specific color stop (0–1).
You can have as many stop elements as you like to create multi-color or complex gradients.