Home > Article > Web Front-end > In-depth understanding of css variables (organized summary)
This article brings you relevant knowledge about css variables. Native css has gradually begun to support nesting, variables and function functions. I hope it will be helpful to everyone.
Anyone who has used sass or less knows that mainly they can have nesting, variables and function functions. In fact, in native css, it has begun to gradually support it. It is true that currently only You and I know it well, but others are still in its infancy. If you understand CSS variables, you will find that CSS has become extremely powerful from now on.
When declaring a variable, two hyphens (--) must be added in front of the variable name
// 局部声明 body { --foo: #ed145b; --bar: #F7EFD2; } // 全局声明 :root{ --foo: #ed145b; --bar: #F7EFD2; }
For example, we declare above 2 variables: --foo and --bar. In fact, you only need to understand them as css custom properties. They are no different from formal properties such as color and font-size, but they have no default meaning. Pay attention to the css variable names. It is case-sensitive, and usually the CSS we write is not case-sensitive.
You may ask, why choose two conjunction lines (--) to represent variables? Because $foo is used by Sass, and @foo is used by Less. In order to avoid conflicts, the official CSS variables use two conjunction lines instead.
Regarding naming, various languages have some indications. For example, CSS selectors cannot start with numbers, and variables in JS cannot be directly numerical. However, in CSS variables In , there are no such restrictions. For example:
:root { --1: #369; } body { background-color: var(--1); }
cannot contain characters such as $, [, ^, (, %, etc. Ordinary characters are limited to "numbers [0-9]" and "letters [a-zA" -Z]", "underscore_" and "dash-" are combinations, but they can be Chinese, Japanese or Korean, for example:
body { --深蓝: #369; background-color: var(--深蓝); }
After declaring the variable We naturally want to obtain and use it, so the var() function is used to read variables
p { color: var(--foo); border::1px solid var(--bar); }
var()The second parameter
color: var(--foo, #ED145B); //第二个参数就是默认值,假设--foo为空情况下,会使用#ED145B
var() function can also be used in Declaration of variables
:root { --primary-color: red; --logo-text: var(--primary-color); // 上面刚声明,这里就可以使用 }
Variable values can only be used as attribute values, not attribute names
.foo { --side: margin-top; /* 很显然,下面是无效的 */ var(--side): 20px; }
If the variable value is a string, it can be used with Other string concatenation
--bar: 'hello'; --foo: var(--bar)' world'; // 示例 body:after { content: '--screen-category : 'var(--screen-category); }
If the variable value is a numerical value, it cannot be used directly with the numerical unit
foo { --gap: 20; /* 下面无效 */ margin-top: var(--gap)px; /* 通过calc去计算,下面有效 */ margin-top: calc(var(--gap) * 1px); }
If the variable value has a unit, it cannot be written as a string
/* 无效 */ .foo { --foo: '20px'; font-size: var(--foo); } /* 有效 */ .foo { --foo: 20px; font-size: var(--foo); }
The same CSS variable can be declared in multiple selectors. When reading, the declaration with the highest priority takes effect. This is consistent with the "cascade" rule of CSS
<style> :root { --color: blue; } div { --color: green; } #alert { --color: red; } * { color: var(--color); } </style> <p>蓝色</p> <div>绿色</div> <div id="alert">红色</div>
In the above code, the three selectors all declare the --color variable. When different elements read this variable, the rule with the highest priority will be used, so the colors of the three paragraphs of text are different.
For browsers that do not support CSS variables, you can use the following writing method.
a { color: #7F583F; color: var(--primary); // 应该很好理解,如果这里读不出值,那么并不会覆盖上面的color }
You can also use the @support command for detection
a { @supports ( (--a: 0)) { /* supported */ } @supports ( not (--a: 0)) { /* not supported */ }
JavaScript can also detect whether the browser supports CSS variables
const isSupported = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0); if (isSupported) { /* supported */ } else { /* not supported */ }
The way JavaScript operates CSS variables is as follows
// 设置变量 document.body.style.setProperty('--primary', '#7F583F'); //局部 document.documentElement.style.setProperty('--primary', '#7F583F'); //全局 // 读取变量 document.body.style.getPropertyValue('--primary').trim(); /局部 document.documentElement.style.getPropertyValue('--primary').trim(); /全局 getComputedStyle(document.documentElement).getPropertyValue('--time'); // 全局,如果是在css表中设置的需要这种方式获取 // '#7F583F' // 删除变量 document.body.style.removeProperty('--primary'); //局部 document.documentElement.style.removeProperty('--primary'); //全局
This means that JavaScript can convert any The value is stored in the style sheet. The following is an example of listening to the event. The event information is stored in the CSS variable
const docStyle = document.documentElement.style; document.addEventListener('mousemove', (e) => { docStyle.setProperty('--mouse-x', e.clientX); docStyle.setProperty('--mouse-y', e.clientY); });
. This means that JavaScript can store any value in the style sheet. The following is an example of listening to the event. Event information is stored in CSS variables
const docStyle = document.documentElement.style; document.addEventListener('mousemove', (e) => { docStyle.setProperty('--mouse-x', e.clientX); docStyle.setProperty('--mouse-y', e.clientY); });
Information that is useless to CSS can also be put into CSS variables
--foo: if(x > 5) this.width = 10;
In the above code, the value of --foo is an invalid statement in CSS. But it can be read by JavaScript. This means that you can write style settings in CSS variables and let JavaScript read them. Therefore, CSS variables provide a way for JavaScript to communicate with CSS.
The browser’s native features can be run directly without any translation
A member of the DOM object, which greatly facilitates the connection between CSS and JS
does not prevent you from using Sass/Less, it can be used in combination
(Learning video sharing: css video tutorial)
The above is the detailed content of In-depth understanding of css variables (organized summary). For more information, please follow other related articles on the PHP Chinese website!