CSSCSS Custom Properties (Variables)

CSS Custom Properties (Variables)

CSS custom properties (variables) store values that can be reused throughout your stylesheets. They're defined with -- prefix and accessed with var(). This enables consistent theming and easier maintenance.

Custom Property Syntax

CSS
/* Define custom properties */
:root {
  --primary-color: #0066cc;
  --secondary-color: #ff6600;
  --spacing-small: 8px;
  --spacing-large: 24px;
  --font-family: Arial, sans-serif;
}

/* Use custom properties */
body {
  color: var(--primary-color);
  font-family: var(--font-family);
}

.button {
  background-color: var(--primary-color);
  padding: var(--spacing-small) var(--spacing-large);
}
Scope and Inheritance

CSS
/* Global scope */
:root {
  --primary-color: blue;
}

/* Scoped variables */
.dark-theme {
  --primary-color: darkblue;
}

/* Inheritance */
.element {
  color: var(--primary-color);
  /* Uses parent's --primary-color */
}

/* Default/fallback values */
.element {
  color: var(--undefined-color, red);
  /* Uses red if --undefined-color not defined */
}
Practical Examples

CSS
/* Design system with variables */
:root {
  /* Colors */
  --color-primary: #0066cc;
  --color-success: #28a745;
  --color-warning: #ffc107;
  --color-danger: #dc3545;

  /* Spacing */
  --space-xs: 4px;
  --space-sm: 8px;
  --space-md: 16px;
  --space-lg: 24px;
  --space-xl: 32px;

  /* Typography */
  --font-size-base: 16px;
  --font-size-lg: 18px;
  --font-size-xl: 24px;
}

/* Dark theme override */
body.dark-mode {
  --color-primary: #4d94ff;
  --bg-color: #1a1a1a;
}
Note
Custom properties enable consistency and easy theming. Define them in :root for global scope. Use var() to access. Fallback values help with compatibility.
Next
Using var(): [Using var() & Fallbacks](/css/using-var).