这是 实验性技术
检查 浏览器兼容性表格 要小心谨慎在生产中使用这之前。

CSS Properties and Values API — part of the CSS Houdini umbrella of APIs — allows the registration of css custom properties , allowing for property type checking, default values, and properties that do or do not inherit their value.

Registering a custom property

Registering a custom property allows you to tell the browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. There are two ways to register a property, in JavaScript or in CSS.

Note: The JavaScript option has working implementations. The CSS option does not.

CSS.registerProperty

The following will register a css custom properties , --my-prop ,使用 CSS.registerProperty , as a color, give it a default value, and have it not inherit its value:

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

@property

The same registration can take place in CSS. The following  will register a css custom properties , --my-prop ,使用 @property , as a color, give it a default value, and have it not inherit its value:

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

Using registered custom properties

One of the advantages of registering a property is that the browser now knows how it should handle your custom property through things like transitions! When a property isn't registered, the browser doesn't know how to treat it, so it assumes that any value can be used and therefore can't animate it. When a property has a registered syntax, though, the browser can optimize around that syntax, including being able to animate it!

In this example, the custom property --registered has been registered using the syntax <color> and then used in a linear gradient. That property is then transitioned on hover or focus to a different color. Notice that with the registered property the transition works, but that it doesn't with the unregistered property!

.registered {
  --registered: #c0ffee;
  background-image: linear-gradient(to right, #fff, var(--registered));
  transition: --registered 1s ease-in-out;
}
.registered:hover,
.registered:focus {
  --registered: #b4d455;
}
.unregistered {
  --unregistered: #c0ffee;
  background-image: linear-gradient(to right, #fff, var(--unregistered));
  transition: --unregistered 1s ease-in-out;
}
.unregistered:hover,
.unregistered:focus {
  --unregistered: #b4d455;
}