css custom properties (css variables)

background

Complex websites will have a lot of CSS code, and often there will be many repeated values.

For example, the same color value may be used in thousands or hundreds of places. If the value changes, it needs to be searched globally and replaced one by one, which is inefficient and error-prone.

Custom properties allow values ​​to be stored in one place and then referenced in multiple other places. Another benefit is semantic identifiers . For example, --main-text-colorthan is easier to understand #00ff00, especially if the same color is used in other contexts as well.

basic usage

1. Declare variables in css

Declare a custom property, the property name needs to --start with two minus signs ( ), and the property value can be any valid CSS value. Like other attributes, custom attributes are also written in the ruleset, as follows:

A common best practice is to define a custom attribute on the :root pseudo-class so that it can be applied globally across the HTML document:

:root {
  --main-bg-color: brown;
}

2. use

You can use custom property values ​​instead of regular property values ​​by specifying the custom property name in the var() function:

element {
  background-color: var(--main-bg-color);
}
Note that the selector provided to the ruleset defines the scope where custom properties can be used, you may limit the scope of custom properties
3. js manipulates css variables
In the JS code, we may need to read the value of the CSS variable, the method is as follows:
const root = document.querySelector(":root");
// 设置 CSS 变量
root.style.setProperty("--main-bg-color", "red");
// 读取 CSS 变量
const computedStyle = getComputedStyle(root);
const mainBgColor = computedStyle.getPropertyValue("--main-bg-color");
console.log(mainBgColor);
// 删除 CSS 变量
root.style.removeProperty("--main-bg-color");

Summary: Flexible use of CSS variables can not only improve productivity, but also improve code readability and maintainability.

Reference blog: Introduction to front-end CSS variables and basic usage methods - Nuggets

Guess you like

Origin blog.csdn.net/u011200562/article/details/125059911