This is the 17th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Read not in the middle of the night five drum, work is work by fits and starts. After watching feel have harvest, point a like bai!!

preface

Most programming languages support variables from the moment the language appears. However, CSS does not support native variables in the first place. So people started to choose SCSS,LESS and other compatible CSS extension languages. Fortunately, CSS now supports variables as well.

Define variables

Variables in JS can live like this:

var variable;
Copy the code

In CSS, variables start with two -.

div { --divWidth: 100px}
Copy the code

Variable scope

Global scope :root

:root {  --bk-color: red}
Copy the code

Local scope

div { --divWidth: 100px}
Copy the code

The same variable can appear in different scopes

div { --divWidth: 100px}
span { --divWidth: 100px}
Copy the code

Variable names are case sensitive

:root { 
  --color: blue;
  --COLOR: red;
}
Copy the code

Use the variable

In SCSS we define and use variables like this:

$font-size: 20px
div {  font-size: $font-size}
Copy the code

In CSS, the var() function is provided to use variables, and the above SCSS can be converted to this

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

Note: Do not use an existing property name as a variable value. Do not use var for property names, either. The following example is incorrect:

:root {  --fontSize: font-size}
.div {  var(--fontSize): 16px}
Copy the code

Can inherit

You can change it in @media

This can be used in the STYLE attribute of HTML

<html lang="en" style="--color: red;" > .father { font-size: 100px; color: var(--color); } <div class="father" --style="">123123</div>Copy the code

How does the browser parse

On the first CSS

:root {
  --color: blue;
}
div {
  --color: green;
}
#child2 {
  --color: red;
} 
* {
  color: var(--color);
}
Copy the code

Using the above variable declaration, what is the color of the following elements?

<p style =" text-align: center; text-align: center; text-align: center;"Copy the code

The first paragraph will be blue. The selector –color is not set to define P directly, so it inherits the value :root

The first div will be green. That’s clear. div { –color: green; } The p of the first div will be green, inherited from div1.

The div’s child2 will not be green. This will be red, #child2 {–color: red; } The p of the first div will be red, inherited from Div2.

JS operation

Modify :root variable

document.body.style.setProperty('--color', '#7F583F');

document.body.style.getPropertyValue('--color').trim();

document.body.style.removeProperty('--color');
Copy the code