Home >Web Front-end >CSS Tutorial >How to Apply Gradients to SVG Rectangles in CSS?

How to Apply Gradients to SVG Rectangles in CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 03:18:29604browse

How to Apply Gradients to SVG Rectangles in CSS?

SVG Gradients in CSS

This question involves applying a gradient to an SVG's element. The following section explains how to implement this functionality in CSS.

Using the fill attribute

Currently, you are using the fill attribute to set a solid color for the element. While this works great for setting a single color fill, it doesn't work well with gradients.

Using gradients

To apply a linear gradient, you need to reference the gradient definition defined in SVG using the url() function. In CSS, the syntax is:

fill: url(#gradient-id);

where #gradient-id is the ID you defined for the gradient in SVG.

Example

The following code shows how to apply a linear gradient to the element:

CSS

rect {
  cursor: pointer;
  shape-rendering: crispEdges;
  fill: url(#MyGradient);
}

SVG

<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <style type="text/css">
    rect {
      fill: url(#MyGradient);
    }
  </style>
  <defs>
    <linearGradient id="MyGradient">
      <stop offset="5%" stop-color="#F60" />
      <stop offset="95%" stop-color="#FF6" />
    </linearGradient>
  </defs>

  <rect width="100" height="50" />
</svg>

This will create a horizontal gradient from red (#F60) to orange (#FF6), applied to the element.

The above is the detailed content of How to Apply Gradients to SVG Rectangles in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn