Web Analytics

CSS Variables

Advanced ~10 min read

What are CSS Variables?

CSS Variables (Custom Properties) let you store values and reuse them throughout your stylesheet. They make maintaining and theming your CSS much easier!

Defining Variables

Define variables with --variable-name and use them with var(--variable-name). Define global variables in :root.

HTML
CSS
JS

Fallback Values

Provide fallback values in case a variable isn't defined: var(--variable, fallback).

HTML
CSS
JS

Variable Scope

Variables are scoped to the element they're defined on and its children. Override global variables locally!

HTML
CSS
JS

Color Themes

Use variables to create switchable themes. Perfect for light/dark mode!

HTML
CSS
JS

Calculations with Variables

Use variables in calc() for dynamic calculations.

HTML
CSS
JS

Design System with Variables

Create a complete design system using CSS variables for colors, spacing, and typography.

HTML
CSS
JS
Pro Tip: Use CSS variables for your entire design system! Define colors, spacing, typography, and more in :root for easy maintenance and theming.

Summary

  • Define: --variable-name: value;
  • Use: var(--variable-name)
  • Fallback: var(--variable, fallback)
  • Global scope: Define in :root
  • Local scope: Override in specific elements
  • Perfect for themes, design systems, and maintainability

Quick Quiz

Where should you define global CSS variables?

A
body
B
:root
C
html
D
*