Reference links: nguyen other CSS notes: www.ruanyifeng.com/blog/2017/0… MDN CSS variables tutorial: developer.mozilla.org/en-US/docs/…

Browser support: mainstream modern browser support

Basic use:

1. Definition:

Declare a CSS variable with the — symbol. The value of the variable can be any value

:root{-main-bg-color: brown;
}
Copy the code

Variable names are case-sensitive and have scopes. Generally, CSS variables are used globally, so they can be placed in :root


2. Scope

:root{-color: red;
}

div{-color: blue;
}

.box {
    height: 100px;
    width: 100px;
    background-color: var(--color);
}
Copy the code
<div class="box"></div>
<p class="box"></p>
Copy the code

Run the HTML code and get a blue div and a red P tag. This is scope-dependent, as well as the priority of the style. When fetching a variable, you get the most precise variable in the scope: ID > class > tag > global

With scopes, we can do two common operations: – (1) media query modifies variables

@media screen and (max-width: 375px) {
  body{-padding: 5px; }}@media screen and (max-width: 1080px) {
  body{-padding: 15px; }}Copy the code

– (2) js switch class name to change theme color

.white-theme {
    --bg-color: #fff;
    --color: # 333;
}

.black-theme {
    --bg-color: # 333;
    --color: #fff;    
}
Copy the code

You can switch different variables by switching the class name with JS. It should be noted that the theme class needs to be in the outermost layer of the node, such as the body or app class, followed by the use of variables where the theme color is needed


3. Call variable:

Call variables using the var() function and the variable name

.red {
    color: var(--theme-color);
}
Copy the code

Variables can only be used as property values, not property names


4. Default values and backward compatibility:

The var() function can take a second argument, which is used as the default value if the variable cannot be found

.red {
    color: var(--theme-color,red);
}

.red {
    color: var(--theme-color, var(--color,red));
}
Copy the code

There is no guarantee that all the devices the user is using will support the CSS variable features, so we can do backward compatibility if necessary: if var does not work, use the previous property value

.red {
    color: red;
    color: var(--theme-color);
}
Copy the code

5. Js manipulation variables

– (1) Checks whether CSS variables are supported

const isSupported =
  window.CSS &&
  window.CSS.supports &&
  window.CSS.supports('--a'.0);

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}
Copy the code

– (2) Operation variable

/ / set
document.body.style.setProperty("--color"."red");

/ / read
document.body.style.getPropertyValue("--color");

/ / delete
document.body.style.removeProperty("--color");
Copy the code

Obviously, JS operation variables need to be in the document environment, in some special occasions can not play a role in the development, such as uniApp multi-terminal.