foreword
In modern browsers, we will often see properties like this:
element {
--main-bg-color: brown;
}
Here we will introduce him and provide some related instructions
Introduction
Custom properties (sometimes called CSS variables or cascading variables) are defined by CSS authors and contain values that can be reused throughout the document. The value is set by the custom attribute tag (eg: --main-color: black;), and the value is obtained by the var() function (eg: color: var(--main-color);)
statement
To declare a custom property, the property name needs to start with two minus signs (--), and the property value can be any valid CSS value.
As in the preface --main-bg-color
attribute
A general best practice is to define it under the root pseudo-class :root
so that it can be accessed anywhere in the HTML document:
/*:root 选择器匹配文档根元素。*/
/*在 HTML 中,根元素始终是 html 元素。*/
/*也就是说:root 表示的是根元素*/
:root {
--main-bg-color: brown;
}
Note: Custom property names are case sensitive, --my-color and --My-color will be considered two different custom properties.
At the same time, it cannot contain characters such as $, [, ^, (, %, etc. The ordinary characters are limited to "number [0-9]", "letter [a-zA-Z]", "underscore_" and "dash-" These combinations, but can be in Chinese, Japanese or Korean, e.g.
body {
--深蓝: #369;
background-color: var(--深蓝);
}
use
element {
background-color: var(--main-bg-color);
}
These custom properties are calculated only when needed, and are not saved according to other rules. For example, you can't set an attribute on an element and then have it get a value from a sibling or descendant rule. Properties are only used to match the current selector and its descendants, just like normal CSS.
Defaults
Multiple fallback values can be defined with the var() function, which will be replaced with fallback values when the given value is undefined.
/*如果提供了第二个参数,则表示备用值,当自定义属性值无效时生效。第二个参数可以嵌套,但是不能继续平铺展开下去了,例如:*/
.two {
color: var(--my-var, red); /* Red if --my-var is not defined */
}
.three {
background-color: var(--my-var, var(--my-background, pink)); /* pink if --my-var and --my-background are not defined */
}
.three {
background-color: var(--my-var, --my-background, pink); /* Invalid: "--my-background, pink" */
}
The second example shows how to handle more than one fallback. This technique can cause performance issues because it spends more time dealing with these variables.
operate in js
Getting or modifying CSS variables in JavaScript is the same as manipulating normal CSS properties:
// 获取一个 Dom 节点上的 CSS 变量
element.style.getPropertyValue("--my-var");
// 获取任意 Dom 节点上的 CSS 变量
getComputedStyle(element).getPropertyValue("--my-var");
// 修改一个 Dom 节点上的 CSS 变量
element.style.setProperty("--my-var", jsVar + 4);
Trailing whitespace feature of CSS variables
body {
--size: 20;
font-size: var(--size)px;
}
Here font-size:var(--size)px
equivalent to font-size:20 px
, note that 20
has a space after it, so here font-size
uses <body>
f509fb5daaa39 <body>
The default size of the element.
scenes to be used
Simple implementation of a progress bar:
There is a background layer outside, and then there is a progress bar and progress value inside.
In the past, two layers of div elements would be used, and then JS would change the width of the color bar inside, and set the progress value at the same time.
<label>图片1:</label>
<div class="bar" style="--percent: 60;"></div>
<label>图片2:</label>
<div class="bar" style="--percent: 40;"></div>
<label>图片3:</label>
<div class="bar" style="--percent: 20;"></div>
.bar {
height: 20px; width: 300px;
background-color: #f5f5f5;
}
.bar::before {
display: block;
counter-reset: progress var(--percent);
content: counter(progress) '%\2002';
width: calc(1% * var(--percent));
color: #fff;
background-color: #2486ff;
text-align: right;
white-space: nowrap;
overflow: hidden;
}
As you can see, we only need one layer of div tags, the DOM level is simple, and then, the HTML change item that needs to be modified is just a --percent custom attribute.
For more scenarios, please refer to this article: https://www.zhangxinxu.com/wordpress/2020/07/css-var-improve-components/
expand
We can extend the CSS variable by @property
:
His grammar:
@property --property-name {
syntax: '<color>';
inherits: false;
initial-value: #c0ffee;
}
@property
rules syntax
and inherits
descriptors are required; if any of these are missing, the entire rule is invalid and ignored.
initial-valu
e descriptor is optional only if syntax
descriptor is generic syntax
defined, otherwise initial-value
is also required If the descriptor is missing at this time, the entire rule will be invalid and ignored.
Of course, we can also use js to create:
window.CSS.registerProperty({
name: '--my-color',
syntax: '<color>',
inherits: false,
initialValue: '#c0ffee',
});
His role, in many cases, is to achieve some animation effects that could not be easily achieved in the past
For details, please refer to this article, which gives several examples: https://juejin.cn/post/6951201528543707150
compatibility
Currently the compatibility of css variables is at least Chrome49:
In CSS we can also do compatibility handling:
.selector: {}
@supports ( (--a: 0)) {
/* supported */
.selector: {}
}
@supports ( not (--a: 0)) {
/* not supported */
.selector: {}
}
Corresponding judgments can also be made in js
const isSupported =
window.CSS &&
window.CSS.supports &&
window.CSS.supports('--a', 0);
And @property
is just an experimental attribute, and its compatibility requirements are very high:
polyfill
https://github.com/jhildenbiddle/css-vars-ponyfill
Compatibility directly attainable using this compatibility:
Chrome 19+
Edge 12+
Firefox 6+
IE 9+
Safari 6+
The current situation
less/sass
In most projects, less/sass/scss is used, but there are already variable functions in these css preprocessing tools. If you use CSS native variables together, it will be redundant
For these preprocessors, we use native css variables to replace the original variables, and the others remain unchanged.
css in js
After the basic CSS is defined in the root, it can be used in js. There is a lot of room for him to play in this framework.
atom css
A commonly used atomic CSS framework: tailwindcss
In this framework, CSS variables are used extensively internally, so if you can use Tailwind, you can use CSS variables
Summarize
The CSS variable function, the current browser support is enough, and for the existing CSS multiple preprocessors, there is a certain degree of adaptation, if you plan to use it, you can try to introduce it
Of course, there is no comprehensive solution right now, and it's okay to wait and see.
quote
- https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
- https://www.zhangxinxu.com/wordpress/2016/11/css-css3-variables-var/
- https://juejin.cn/post/6937530846471520287
- https://www.zhangxinxu.com/wordpress/2020/07/css-var-improve-components/
- https://developer.mozilla.org/en-US/docs/Web/CSS/@property#browser_compatibility
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。