CSS custom properties for cascading variables

فهرست فصل‌ها دانلود آرشیوناشر

MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونه‌کد

The CSS custom properties for cascading variables module adds support for cascading variables in CSS properties and lets you create custom properties to define these variables along with the mechanisms to use custom properties as the values for other CSS properties.

When working with CSS, you often end up reusing common project-specific values such as widths that work well with your layout, or a set of colors for your color scheme. One way of managing repetition in stylesheets is to define a value once and use it many times in other places. Custom properties let you create and define custom variables that can be reused, simplifying complex or repetitive rules and making them easier to read and maintain. For example, --dark-grey-text and --dark-background are easier to understand than hexadecimal colors such as #323831, and the context of how you use them is more obvious, too.

Custom properties in action

To see how custom properties can be used, move the input slider left to right.

html hidden
js hidden
css hidden

{{EmbedLiveSample("Custom properties in action",600,160)}}

In these color swatches, the {{cssxref("background-color")}} is set using the {{cssxref("color_value/hsl", "hsl()")}} {{cssxref("<color>")}} function as hsl(var(--hue) 50% 50%). Each color swatch increments the {{cssxref("hue")}} value by 10 degrees like calc(var(--hue) + 10), calc(var(--hue) + 20) etc. As the slider's value changes from 0 up to 360, the value of the --hue custom property is updated using {{cssxref("calc")}}, and the background color of each box inside the grid is updated, also.

Reference

Properties

  • {{cssxref("--*")}}

Functions

  • {{cssxref("var")}}

Guides

  • Invalid custom properties
  • : Explains how browsers handle property values when a custom property's value is an invalid data type for that property.

Related concepts

  • CSS Properties and Values API module
  • {{cssxref("@property")}} at-rule
  • [CSS.registerProperty()](/en-US/docs/Web/API/CSS/registerProperty_static) method

Specifications

{{Specifications}}

See also

  • CSS cascading and inheritance module
  • [CSS env()](/en-US/docs/Web/CSS/Reference/Values/env) function
  • [CSS calc()](/en-US/docs/Web/CSS/Reference/Values/calc) function
  • [getPropertyValue()](/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue) method