@property

Baseline 2024
Newly available

Since July 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

@property CSS at-ruleCSS Houdini API 的一部分,它允许开发者显式地定义他们的CSS 自定义属性, 允许进行属性类型检查、设定默认值以及定义该自定义属性是否可以被继承。

@property 规则提供了一个直接在样式表中注册自定义属性的方式,而无需运行任何 JS 代码。有效的 @property 规则会注册一个自定义属性,就像 CSS.registerProperty 函数被使用同样的参数调用了一样。

Syntax(语法描述符)

css
@property --property-name {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

一个有效的 @property 规则代表一项自定义属性的注册,使用自定义属性名作为规则内代码序列的序部。

@property 规则中 syntaxinherits 描述符是必需的; 如果其中任何一项缺失,整条规则都将失效并且会被忽略。 initial-value 描述符仅在 syntax 描述符为通用 syntax 定义时是可选的,否则initial-value也是必需的——如果此时该描述符缺失,整条规则都将失效且被忽略。

未知的描述符自身都是无效的,且会被忽略。但是不会造成整条@property规则的失效。

实例

--my-color 自定义属性添加颜色值类型检测、设置默认值并且设置属性值不允许被继承。

使用 CSS @property 规则:

css
@property --my-color {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

使用 JavaScript 中的 CSS.registerProperty函数:

js
window.CSS.registerProperty({
  name: "--my-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee",
});

标准语法

css
@property =   @property <custom-property-name> { <declaration-list> }  

规范

Specification
CSS Properties and Values API Level 1
# at-property-rule

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
@property
inherits descriptor
initial-value descriptor
syntax descriptor

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见