Codectionary / Developer documentation / CSS

Custom Properties (CSS Variables)

Custom properties, written as --name, let you define reusable values directly in CSS, accessed with var(). Unlike Sass variables, they are live in the browser - they can be read and changed with JavaScript, and they respect the cascade, meaning their value can be different in different parts of the DOM.

Syntax

--name: value;
var(--name, fallback);

Examples

Defining and Using Variables

A typical theming setup using custom properties on :root.

:root {
  --primary-color: #3b82f6;
  --spacing-unit: 8px;
  --border-radius: 6px;
}

.button {
  background: var(--primary-color);
  padding: calc(var(--spacing-unit) * 2);
  border-radius: var(--border-radius);
}

Scoped Overrides and Fallbacks

Custom properties respect the cascade, so they can be overridden in specific contexts.

.dark-theme {
  --primary-color: #60a5fa; /* overrides the root value just within this scope */
}

.button {
  color: var(--text-color, black); /* falls back to black if --text-color is not defined */
}

Parameters and values

  • --name: value; (declaration): Defines a custom property, commonly on :root for global scope
  • var(--name) (function): Reads a custom property's current value
  • var(--name, fallback) (function): Uses a fallback if the custom property is not defined

Best practices

  • Define global theme variables on :root, and override them locally on specific components or contexts (like a .dark-theme class) as needed
  • Provide a fallback value in var() for properties that might not always be defined, like var(--gap, 1rem)
  • Take advantage of custom properties being live and JavaScript-readable for dynamic theming without regenerating an entire stylesheet
  • Use meaningful, consistent naming conventions (--color-primary, --spacing-sm) as a project grows, similar to a design token system

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation