What are CSS custom properties?

CSS custom properties (often called CSS variables) are author-defined properties whose names start with --, read with var(). They cascade and inherit like normal properties, are evaluated at computed-value time in the browser, and can be registered with @property to give them a type, default value and the ability to animate.

How they work under the hood

  • They are inherited by default and resolved per element, so the same var(--gap) can mean different values in different parts of the tree.
  • Values are stored as unparsed token streams; they are only validated where they are used. An invalid substitution makes the property "invalid at computed-value time" and it falls back to its inherited or initial value, not to an earlier declaration.
  • Fallback chains: var(--a, var(--b, 16px)).

@property: typed custom properties

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

Benefits:

  • They become animatable. Gradients normally cannot transition, but a typed --angle used inside a conic-gradient can.
  • Type checking and a guaranteed initial value.
  • inherits: false improves performance for frequently changing values.

Practical patterns

  • Design tokens and theming.
  • "Private" component APIs: .btn { --_bg: var(--btn-bg, var(--brand)); background: var(--_bg); }.
  • Space toggles and state-driven styles with :has().
  • Passing values from JavaScript: style="--progress: 0.6".

Performance tip

Changing a custom property on :root invalidates styles for the whole document; set frequently changing ones on the smallest element possible.

Code example

html
1<style>
2 @property --angle {
3 syntax: "<angle>";
4 inherits: false;
5 initial-value: 0deg;
6 }
7 @property --progress {
8 syntax: "<number>";
9 inherits: true;
10 initial-value: 0;
11 }
12 body { font-family: system-ui; }
13 .ring {
14 width: 120px; aspect-ratio: 1; border-radius: 50%;
15 background: conic-gradient(from var(--angle), #2b4bff, #e11d48, #ffd84d, #2b4bff);
16 animation: spin 3s linear infinite; /* only possible because --angle is typed */
17 }
18 @keyframes spin { to { --angle: 360deg; } }
19 .bar { height: 14px; width: 260px; border: 2px solid #0b1020; margin-top: 16px;
20 background: linear-gradient(90deg, #059669 calc(var(--progress) * 100%), #e5e7eb 0);
21 transition: --progress .6s ease; }
22</style>
23<div class="ring" role="img" aria-label="Animated gradient ring"></div>
24<div class="bar" id="bar" style="--progress: .2"></div>
25<button onclick="bar.style.setProperty('--progress', Math.random().toFixed(2))">Random progress</button>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app