Linear Gradients in SVG
- Previous Page Shadows in SVG
- Next Page Radial Gradients in SVG
SVG Gradients
Gradients are smooth transitions from one color to another. In addition, multiple color transitions can be applied to the same element.
There are two main types of gradients in SVG:
- Linear Gradient
- Radial Gradient
SVG Linear Gradient - <linearGradient>
<linearGradient>
The element is used to define linear gradients.
<linearGradient>
The element must be nested within <defs>
within the tag.<defs>
The element is an abbreviation for definitions, which includes definitions of special elements (such as filters).
Linear gradients can be defined as horizontal, vertical, or angular gradients:
- Create a horizontal gradient when y1 and y2 are equal and x1 and x2 are not equal
- Create a vertical gradient when x1 and x2 are equal and y1 and y2 are not equal
- Create an angular gradient when x1 and x2 are different and y1 and y2 are not equal
Example 1
Define an ellipse with a horizontal linear gradient from yellow to red:
This is the SVG code:
<svg height="150" width="400"> <defs> <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" /> <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" /> </linearGradient> </defs> <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" /> </svg>
Code Explanation:
- The id attribute of the <linearGradient> tag defines the unique name of the gradient
- The x1, x2, y1, y2 attributes of the <linearGradient> tag define the start and end positions of the gradient
- The color range of the gradient can be composed of two or more colors. Each color is specified by a <stop> tag
- The offset attribute is used to define the start and end positions of the gradient color
- The fill attribute links the ellipse element to the gradient
Example 2
Define an ellipse with a vertical linear gradient from yellow to red:
This is the SVG code:
<svg height="150" width="400"> <defs> <linearGradient id="grad2" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" /> <stop offset="100%" style="stop-color:rgb(255,255,0);stop-opacity:1" /> </linearGradient> </defs> <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad2)" /> </svg>
Example 3
Define an ellipse and add text inside it, with a horizontal linear gradient from yellow to red:
This is the SVG code:
<svg height="150" width="400"> <defs> <linearGradient id="grad3" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" /> <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" /> </linearGradient> </defs> <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad3)" /> <text fill="#ffffff" font-size="45" font-family="Verdana" x="150" y="86"> SVG</text> </svg>
Code Explanation:
- The <text> element is used to add text
- Previous Page Shadows in SVG
- Next Page Radial Gradients in SVG