SVG Linear Gradients
Photo Credit to CodeToFun
🙋 Introduction
SVG (Scalable Vector Graphics) provides a powerful way to create vector graphics for the web. One of the advanced features in SVG is the ability to apply linear gradients to shapes. Linear gradients create a smooth transition between two or more colors along a straight line, adding depth and dimension to your graphics.
In this guide, we will explore how to create and use SVG linear gradients.
💡 Syntax
To define a linear gradient in SVG, you use the <linearGradient>
element within a <defs> block, followed by the <stop> elements to specify the gradient colors. The gradient is then applied to an SVG shape using the fill attribute. Here's the basic structure:
<svg>
<defs>
<linearGradient id="gradientID" x1="start-x" y1="start-y" x2="end-x" y2="end-y">
<stop offset="percentage" stop-color="color" />
<!-- Add more <stop> elements as needed -->
</linearGradient>
</defs>
<shape fill="url(#gradientID)" />
</svg>
🧰 Attributes
- id: A unique identifier for the gradient.
- x1, y1: Coordinates for the starting point of the gradient (usually 0%).
- x2, y2: Coordinates for the ending point of the gradient (usually 100%).
- offset: Specifies where the gradient stop is placed, typically a percentage (e.g., "0%", "50%", "100%").
- stop-color: The color at the gradient stop.
📄 Example
Let's create an SVG rectangle filled with a linear gradient:
<svg width="200" height="200">
<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>
<rect width="200" height="200" fill="url(#grad1)" />
</svg>
🧠 How it works?
In this example, we define a linear gradient that transitions from yellow to red horizontally. The gradient is then applied to a rectangle that fills the entire SVG canvas.
🎉 Conclusion
SVG linear gradients enhance the visual appeal of your graphics by allowing smooth color transitions. They are easy to implement and highly customizable, making them a valuable tool for web designers and developers.
By mastering linear gradients, you can add a professional touch to your SVG artwork.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (SVG Linear Gradients), please comment here. I will help you immediately.