The three main things you should know when using CSS variables
- Custom properties
- var () function
- : Root Pseudo class
One, custom properties
We can define the reused property as a custom property, so that we need to modify the property value in the custom attribute only when we have to change it later.
: root {
--textcolor: #444;
}
The code above is the way to write custom attributes, and it is important to note that the custom attributes begin with
Two, Var () function
We need to use the Var () function to read the variable, otherwise the browser doesn't know what your custom attribute is.
The Var () function can also specify a second property, which represents the default value of the property
p {
Color:var (--textcolor);
}
To set the font color of the P tag, you can write it like the code above
It's the same as p {color: #444;}
Three, Root pseudo class
Before you say the root pseudo class, let's start by talking about the scope of CSS custom properties.
The same CSS custom attribute, which can be declared in multiple selectors, is read with the highest priority attribute in effect.
Body {
--bgcolor:red;
}
. Content {
--textcolor:blue;
}
The code above, the scope of-bgcolor is body, the scope of--textcolor is. Content for this reason, it is best to place the custom attribute in the root element: root, so that any selector can read them.
How to use variables in CSS