css - @property rule

The @property rule in CSS is used to define custom properties (CSS variables) with specific types, default values, and inheritance behavior. It was introduced as part of the CSS Houdini API, allowing you to create more powerful and dynamic CSS variables, especially for animations and transitions.


1. Basic Syntax

@property --variable-name {
  syntax: '<data-type>';
  inherits: true | false;
  initial-value: <default-value>;
}

Parameters

  • --variable-name → The custom property name.

  • syntax → Defines the type of value (color, number, length, etc.).

  • inherits → Determines whether the property is inherited by child elements.

  • initial-value → Default value if not set anywhere.


2. Example: Defining a Custom Color Property

@property --main-color {
  syntax: '<color>';
  inherits: false;
  initial-value: #4caf50;
}

.box {
  width: 200px;
  height: 200px;
  background-color: var(--main-color);
}
  • Here, we define --main-color as a color variable.

  • If we don’t set it manually, it defaults to green.


3. Why Use @property Instead of Normal CSS Variables

Normally, CSS variables cannot be animated smoothly because the browser doesn’t know their type.
But when you declare them with @property, you unlock animations.


4. Animating a Custom Property

Without @property → No Smooth Animation

.box {
  --angle: 0deg;
  transform: rotate(var(--angle));
  transition: --angle 2s; /* ❌ Doesn't work */
}

With @property → Smooth Animation

@property --angle {
  syntax: '<angle>';
  inherits: false;
  initial-value: 0deg;
}

.box {
  width: 100px;
  height: 100px;
  background: tomato;
  transform: rotate(var(--angle));
  transition: --angle 2s;
}

.box:hover {
  --angle: 180deg;
}

Result:
When you hover, the box rotates smoothly from 0deg to 180deg.


5. Supported Data Types

Syntax Value Description Example
<color> Colors #ff0000, rgb(255,0,0)
<length> Units of length 10px, 5em, 50%
<angle> Rotations/angles 45deg, 0.5turn
<number> Numeric values 1, 2.5
<percentage> Percentages 50%, 100%
<length-percentage> Length or percentage 50px, 30%

6. Using @property for Light/Dark Theme

@property --bg {
  syntax: '<color>';
  inherits: true;
  initial-value: #ffffff;
}

@property --text {
  syntax: '<color>';
  inherits: true;
  initial-value: #000000;
}

body {
  background-color: var(--bg);
  color: var(--text);
  transition: --bg 0.5s, --text 0.5s;
}

body.dark {
  --bg: #222;
  --text: #fff;
}

Effect:

  • Smooth transition between light mode and dark mode.


7. Browser Support

  • Chrome ✅ (Fully supported)

  • Edge

  • Safari

  • Firefox ❌ (Still experimental)

For better compatibility, always provide a fallback.


8. When to Use @property

  • When you want smooth animations of CSS variables.

  • When defining typed variables like angles, colors, or lengths.

  • When working with themes and transitions.

  • When using Houdini APIs for advanced CSS effects.