In order to unify the page style in the preparation of CSS style files often a large number of reuse of the same color or font, aggravating the development workload is not conducive to the later maintenance, so the need to use CSS global variables.

Declare global variables

CSS global variables are declared with two center dashes before their names.

body {
  --Color: #2C51CD;
  --BackGround: #B4D4FD;
}
Copy the code

In the code above, Color and BackGround are declared in the body selector. Use – because $is occupied by Sass and @ is occupied by Less.

Variable declarations are case sensitive. For example, Color and Color represent two different variables.

Read the variable

Use the var() function to read variables.

p {
  background: var(--Color);
}
Copy the code

The var() function can also take a second argument that represents the default value of the variable. If the variable does not exist, the default value is used.

p {
  background: var(--Color, #2C51CD);
}
Copy the code

The second argument does not handle internal commas or Spaces, which are treated as part of the argument.

p {
  font-family: var(--fontF, "Roboto"."Helvetica");
  margin: var(--Margins, 15px 20px 25px);
}
Copy the code

The var() function can also be used in variable declarations

body {
  --Color: #2C51CD;
  --BackGround: var(--Color);
}
Copy the code

A variable can only be an attribute value, not an attribute name

The type of a variable value

If the variable value is a string, it can be concatenated with other strings

:root {
  --Hi: 'hello';
  --Name: var(--Hi)',world';
}
Copy the code

If the value is a numeric value, it cannot be spliced

:root {
  --pSizeVal: 20;
  --pSize: var(--pSizeVal)'px'; / / is invalid}
Copy the code

But you can splice them together with the calc() function

:root {
  --pSizeVal: 20;
  --pSize: calc(var(--pSizeVal)*1px);
}
Copy the code

If the variable value has a unit, it cannot be written as a string

:root {
  --pSize: '20px';
  margin-top: var(--pSize); / / is invalid}

:root {  --pSize: 20px;  margin-top: var(--pSize); / / effective} Copy the code

scope

The scope of a variable is the valid scope of its selector.

<style>
  :root {
    --Color: blue;
  }
  div {
 --Color: green;  }  #alert {  --Color: red;  }  * {  color: var(--Color);  } </style>  <p> blue < /p> <div> green < /div> <div id="alert"> red < /div> Copy the code

In the code above, all three selectors are declared –Color variable. Each element reads the variable with the highest precedence, so the color of the three paragraphs is different.

So some generic variable values are best declared inside –root{}.

Go from CSS variables: Declare global variables to make writing faster –root

This article is formatted using MDNICE