CSS 属性和值 API

CSS 属性和值 API(CSS Properties and Values API)——CSS Houdini API 的一部分——允许开发者显式地定义它们的 CSS 自定义属性,允许设置属性类型检查、默认值以及是否可继承其值。

接口

CSS.registerProperty

定义了浏览器应该如何解析 CSS custom properties。通过 JavaScript 中的 CSS.registerProperty 访问该接口。

@property

定义了浏览器应该如何解析 CSS custom properties。通过 CSS 中的 @property at 规则访问该接口。

示例

以下代码在 JavaScript 中使用 CSS.registerProperty 输入一个 CSS 自定义属性--my-color,将其作为一个颜色,然后为其设置一个默认值,并且不允许继承它的值。

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

可以在 CSS 中使用 @property at-rule 进行相同的注册:

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

规范

Specification
CSS Properties and Values API Level 1
# the-css-property-rule-interface
CSS Properties and Values API Level 1
# the-registerproperty-function

浏览器兼容性

api.CSSPropertyRule

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
CSSPropertyRule
inherits
initialValue
name
syntax

Legend

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

Full support
Full support

api.CSS.registerProperty_static

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
registerProperty() static method

Legend

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

Full support
Full support

参见