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
Release: 2024-11-03 03:18:29
Original
588 people have browsed it

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);
Copy after login

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);
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template