CSS – @property Rule

CSS @property Rule

The @property rule is used to define custom CSS properties directly in the stylesheet without having to run any JavaScript.

The @property rule has data type checking and constraining, sets default values, and defines whether the property can inherit values or not.

Example of defining a custom property:

@property --myColor {
  syntax: "";
  inherits: true;
  initial-value: lightgray;
}

The definition above says that –myColor is a color property, it can inherit values from parent elements, and its default value is lightgray.

To use the custom property in CSS, we use the var() function:

body {
  backgound-color: var(--myColor);
}

The benefits of using @property:

  • Type checking: You must specify the data type of the custom property, such as <number>, <color>, <length>, etc. This prevents errors and ensures that custom properties are used correctly
  • Set default value: You set a default value for the custom property. This ensures that if an invalid value is assigned later, the browser uses the defined fallback value
  • Set inheritance behavior: You must specify whether the custom property can inherit values from its parent elements or not

Continue reading CSS – @property Rule