HTML&CSS · December 20, 2023

Css Basic: gradientUnits

CSS Basics: gradientUnits

In CSS, gradients are a popular way to add visual interest and depth to backgrounds and elements. With the gradientUnits property, you can control how the gradient is rendered and positioned within an element.

Understanding gradientUnits

The gradientUnits property is used in conjunction with the linear-gradient() and radial-gradient() functions to define the coordinate system for the gradient. It determines whether the gradient is sized and positioned relative to the element's bounding box or the entire page.

There are two possible values for the gradientUnits property:

  • objectBoundingBox: This value specifies that the gradient is sized and positioned relative to the bounding box of the element. The bounding box is the smallest rectangle that encloses the element's content, padding, and border.
  • userSpaceOnUse: This value specifies that the gradient is sized and positioned relative to the entire page. It uses the coordinate system of the SVG viewport, which is typically the size of the browser window.

Examples

Let's take a look at some examples to understand how the gradientUnits property works.

Example 1: objectBoundingBox

.gradient {
  background: linear-gradient(to right, red, blue);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  gradientUnits: objectBoundingBox;
}

In this example, the gradient is applied to the text within an element. The gradientUnits property is set to objectBoundingBox, which means the gradient is sized and positioned relative to the bounding box of the text. This ensures that the gradient is contained within the text and doesn't overflow to the surrounding area.

Example 2: userSpaceOnUse

.gradient {
  background: radial-gradient(circle, yellow, green);
  gradientUnits: userSpaceOnUse;
}

In this example, the gradient is applied to the background of an element. The gradientUnits property is set to userSpaceOnUse, which means the gradient is sized and positioned relative to the entire page. This allows the gradient to cover the entire background of the element, regardless of its size or position.

Conclusion

The gradientUnits property in CSS allows you to control how gradients are sized and positioned within elements. By understanding the two possible values, objectBoundingBox and userSpaceOnUse, you can create visually appealing gradients that enhance the design of your website.

Summary

In summary, the gradientUnits property in CSS is used to define the coordinate system for gradients. It can be set to objectBoundingBox or userSpaceOnUse. To learn more about CSS and how it can enhance your website, visit Server.HK.