🌐

CSS Custom Properties (Variables): A Complete Guide

HTML/CSS5 min read

Master CSS custom properties to create maintainable, themeable stylesheets.

CSS custom properties (variables) store values that can be reused throughout your stylesheet. They're defined with -- prefix and accessed with var(). Unlike preprocessor variables, they cascade and can be changed dynamically.

Define variables on :root for global scope: :root { --primary: #3b82f6; --spacing: 1rem; }. Use them anywhere: color: var(--primary); padding: var(--spacing).

Variables can be overridden in specific scopes: .dark-theme { --bg: #1f2937; --text: white; }. This enables easy theming without duplicating CSS. JavaScript can modify them: element.style.setProperty("--color", "red").

Use calc() with variables for dynamic calculations: width: calc(var(--base-width) * 2). Fallback values: var(--color, blue) uses blue if --color isn't defined.

Experiment with CSS variables in CompileZ's HTML editor. Create a theme switcher that changes colors by updating custom properties.

Related Articles