DEV Community

Moritz Schramm
Moritz Schramm

Posted on

5 1

Creating linear gradients in SVG

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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%">.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs