With the popularity of SASS, LESS, POSTCss, the native CSS standard has also been promoted, although there is no cascade definition, but CSS has begun to support CSS Variables can also be called CSS Custom properties, so that we can not only reuse attribute values, It can also be dynamically changed through Javascript to achieve animation effects.

Definition of CSS variables

To define CSS variables, you simply prefix them with –. For example, to set the size variable, write –size. To use variables, you need to use the var() CSS function

div{
    --size: 16px;
    font-size: var(--size);
}
Copy the code

This is the easiest way to use CSS variables, but it is important to note that CSS variables are scoped. For example, if I define –size in

Do you remember the root selector? Yes, you can use this selector to set CSS variables in the root element, which is equivalent to global variables, so let’s do another chestnut.

:root{
    --size: 16px;
}

div {
    font-size: var(--size);
}
Copy the code

The concept of CSS variables and default values, let’s take a look at one

div {
    --text-color: pink;
    color: var(--text-color, black);
}
Copy the code

The second argument to the var() function is the default value. If –text-color is undefined, black is used. Give me another chestnut.

div{
    --text-color1: pink;
    --text-color2: yellow;
    color: var(--text-color1, --text-color2, black);
}
Copy the code

That will do. NO!!!! This is the wrong way !!!! The correct way to write it is this

div{
    --text-color1: pink;
    --text-color2: yellow;
    color: var(--text-color1, var(--text-color2, black));
}
Copy the code

Multiple defaults can be achieved by reusing the var() function.

OK, more usage methods will be broken down later, that’s all for today