1.以前定义变量
:root {
--whiteColor: #fff;
}
p {
color: (--whiteColor);
}
2.@property定义变量
<style>
@property --property-name {
syntax: '<color>';
inherits: false;
initial-value: #fff;
}
p {
color: var(--property-name);
}
</style>
简单解读下:
@property --property-name
中的--property-name
就是自定义属性的名称,定义后可在 CSS 中通过var(--property-name)
进行引用- syntax:该自定义属性的语法规则,也可以理解为表示定义的自定义属性的类型
- inherits:是否允许继承
- initial-value:初始值
其中,@property
规则中的 syntax 和 inherits 描述符是必需的。
支持的 syntax 语法类型
syntax
支持的语法类型非常丰富,基本涵盖了所有你能想到的类型。
- length
- number
- percentage
- length-percentage
- color
- image
- url
- integer
- angle
- time
- resolution
- transform-list
- transform-function
- custom-ident (a custom identifier string)
syntax 中的 +
、#
、|
符号
定义的 CSS @property
变量的 syntax 语法接受一些特殊的类型定义。
syntax: '<color#>'
:接受逗号分隔的颜色值列表syntax: '<length+>'
:接受以空格分隔的长度值列表syntax: '<length | length+>'
:接受单个长度或者以空格分隔的长度值列表
OK,铺垫了这么多,那么为什么要使用这么麻烦的语法定义 CSS 自定义属性呢?CSS Houdini 定义的自定义变量的优势在哪里?下面我们一一娓娓道来。
@property --houdini-colorA {
syntax: '<color>';
inherits: false;
initial-value: #fff;
}
@property --houdini-colorB {
syntax: '<color>';
inherits: false;
initial-value: #000;
}
.property {
background: linear-gradient(45deg, var(--houdini-colorA), var(--houdini-colorB));
transition: 1s --houdini-colorA, 1s --houdini-colorB;
&:hover {
--houdini-colorA: yellowgreen;
--houdini-colorB: deeppink;
}
}