Chuyển đến nội dung

Bài 111 · Modern CSS

@property and Typed Custom Properties

Register custom properties with @property to give them a type, an initial value and controlled inheritance, then animate gradients, counters and sizes.

Ordinary custom properties are untyped. To the browser, --size: 20px is just a string of text that happens to be stored under a name. It substitutes that text wherever you write var(--size), and only then does the property it landed in decide whether the text makes sense. That is flexible, but it has three limits: a custom property can't be animated smoothly, it has no default if you forget to set it, and it always inherits.

The @property rule removes all three limits. It registers a custom property: you tell the browser its type, its initial value and whether it inherits. With a type, the browser knows how to interpolate between two values, and a whole family of effects becomes possible with plain CSS. This lesson covers the syntax, the types, and the practical recipes.

The rule

A registration has a name and up to three descriptors:

CSS
@property --progress {
  syntax: "<percentage>";
  inherits: false;
  initial-value: 0%;
}
  • syntax is a string describing which values are allowed ("<length>", "<color>", "<number>" and so on).
  • inherits is true or false. It is required.
  • initial-value is the starting value. It is required unless syntax is the universal "*", and it must be a valid, computationally independent value for the type (0% is fine, but 1em is not allowed because it depends on the element's font size).

These look like properties, but inside @property they are descriptors (see CSS At-Rules). You can also register from JavaScript with CSS.registerProperty({ name, syntax, inherits, initialValue }), but the CSS version is preferred because the browser reads it before the first paint.

flowchart TD
  A["Declaration: --angle: 90deg"] --> B{"Registered with @property?"}
  B -- "No" --> C["Stored as untyped text<br/>no interpolation"]
  B -- "Yes" --> D{"Value matches syntax?"}
  D -- "Yes" --> E["Typed value<br/>can animate and transition"]
  D -- "No" --> F["Invalid at computed time<br/>falls back to initial-value"]

Registration gives the browser a type to check and interpolate. A value that fails the check falls back to the initial value.

Syntax strings

The syntax descriptor takes one or more data type names in angle brackets:

Syntax Accepts Example value
"<length>" A length 12px, 2rem
"<percentage>" A percentage 40%
"<length-percentage>" Either calc(10px + 5%)
"<number>" A real number 0.5
"<integer>" A whole number 3
"<angle>" An angle 45deg, 0.25turn
"<time>" A duration 300ms
"<color>" Any color #4f46e5, oklch(...)
"<image>" An image or gradient url(...)
"<transform-function>" One transform rotate(10deg)
"*" Anything (untyped) the default behavior

You can combine types with | ("<length> | auto"), allow a space-separated list with + ("<length>+") and a comma-separated list with # ("<color>#"). Keywords are written bare: "none | <image>". Typed values are also computed at the time they are read, so a registered <length> containing 2em becomes an absolute length. That is why em is not allowed in an initial value but is fine in an actual declaration.

Recipe 1: animating a gradient

A gradient is not animatable in itself, because a browser can't smoothly interpolate between two linear-gradient() images. But its angle is just a number. If the angle lives in a registered <angle> property, the browser can animate it:

A conic gradient that rotates smoothly

The element itself doesn't rotate. Only the number inside the gradient changes, and you could just as well animate a gradient's color stop or the position of a spotlight. Without the @property rule, the keyframes would "snap" from 0deg to 360deg at the end, because the browser can't interpolate untyped text.

Recipe 2: a theme color that transitions

Normally a theme switch changes custom properties instantly, because untyped properties can't be transitioned. Register them as <color> and a transition makes the whole interface fade between themes:

CSS
@property --accent {
  syntax: "<color>";
  inherits: true;
  initial-value: #4f46e5;
}

:root { transition: --accent 400ms ease; }
[data-theme="warm"] { --accent: #ea580c; }

Every rule that uses var(--accent) now blends smoothly when the theme changes (see Design Tokens and Theming). Note the inherits: true: tokens that the whole page shares should inherit, as unregistered ones always do.

Recipe 3: an animated counter

A registered <integer> can be animated, and a CSS counter can display it. The value moves through whole numbers because the type is integer:

Counting up with an animated integer

The generated text from content is not a good place for important information (see Accessibility). Treat this as a visual flourish.

Controlling inheritance

Unregistered custom properties always inherit. That is usually what you want for tokens, but it causes a subtle trap with component variables: a nested component accidentally inherits a variable from its parent component.

With inherits: false, a registered property resets to its initial-value on every element that does not set it itself:

CSS
@property --card-pad {
  syntax: "<length>";
  inherits: false;
  initial-value: 1rem;
}

.card { padding: var(--card-pad); }
.compact { --card-pad: 0.5rem; }   /* affects the .compact element only */

Without registration, a card placed inside a .compact section would inherit 0.5rem, even if it should be roomy. With inherits: false, only elements that set --card-pad themselves use it. This turns custom properties into real component-private parameters.

Defaults and error handling

A registered property is never "unset" in the guaranteed-invalid sense. It always has a value:

  • If you never set it, it's the initial-value. You no longer need var(--x, fallback) everywhere.
  • If you set a value that does not match the syntax, the declaration is ignored at computed-value time and the property becomes inherit or initial, depending on inherits.
CSS
@property --gap {
  syntax: "<length>";
  inherits: false;
  initial-value: 8px;
}
.row { --gap: banana; gap: var(--gap); }   /* banana fails the check: the gap is 8px */

This predictable fallback is another reason to register important parameters. It also means that a var() fallback written next to a registered property is no longer needed for undefined cases, though fallbacks still help in older browsers.

Support and progressive enhancement

@property works in current Chrome, Edge, Safari and Firefox (Firefox added it in version 128, mid-2024). In a browser that ignores the rule, the custom property still works as an ordinary untyped variable, but it won't animate. Design for that:

  • Make sure the page looks right with the non-animated version.
  • If you need to branch, check CSS.registerProperty in JavaScript as in the first example, or see Feature Queries for CSS-side checks.
  • Remember motion preferences. Infinite background animation should respect prefers-reduced-motion, as covered in Motion and Performance.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why can't an unregistered custom property be animated smoothly?

    Without a type, the value is untyped text. Registering a type lets the browser interpolate numbers, angles, colors and so on.
  2. 2. Which descriptor is required in every @property rule, besides syntax?

    inherits must be present. initial-value is also required unless the syntax is *.
  3. 3. What happens when a registered <length> property receives the value banana?

    A value that doesn't match the registered syntax is invalid at computed-value time, so the property doesn't hold it.
  4. 4. What is the practical effect of inherits: false?

    Children reset to the initial value unless they set the property themselves, which makes component variables private.
  5. 5. Why is initial-value: 1em invalid for a <length> property?

    Initial values must be computationally independent. Use absolute units like px or rem.

Summary

  • @property registers a custom property with a syntax, inherits and initial-value.
  • Typed properties can be animated and transitioned: gradient angles, theme colors, integers and sizes.
  • Syntax strings use data types such as <length>, <color> and <angle>, combined with |, + and #.
  • Registered properties always have a value: the initial value is the default, and invalid values are ignored.
  • inherits: false makes a custom property private to the elements that set it.
  • Support is broad since 2024, but treat animation as an enhancement and respect reduced motion.

Next: Dark Mode.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.