CSS Properties & Values API
The CSS Properties and Values API is part of the CSS Houdini umbrella of APIs.
Getting Started
The CSS Properties & Values API allows developers to explicitly define their custom CSS properties, specifying their type, initial value, and inheritance behavior. This provides more control and enables new possibilities like animated custom properties.
First, you register a custom property using JavaScript:
if (typeof CSS !== 'undefined' && CSS.registerProperty) {
CSS.registerProperty({
name: '--my-color',
syntax: '<color>',
initialValue: 'black',
inherits: false
});
} else {
console.log("CSS.registerProperty is not supported in this browser.");
}
In this example, we register a custom property named --my-color
. We define its syntax as a color, set its initial value to 'black', and specify that it does not inherit.
Then, you can use this registered property in your CSS:
.my-element {
--my-color: blue;
background-color: var(--my-color);
transition: --my-color 1s;
}
.my-element:hover {
--my-color: red;
}
Because --my-color
is registered with a defined syntax (e.g., '