CSS Custom Properties (Variables)

CSS variables (custom properties) allow you to store and reuse values throughout your stylesheets.

Using Variables

Define variables with -- prefix: --primary-color: blue;

Use variables with var() function: color: var(--primary-color);

Variables cascade and can be scoped to elements.

Define globals in :root pseudo-class.

Provide fallback values: var(--color, blue);

/* Define variables */
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --spacing: 20px;
  --border-radius: 5px;
}

/* Use variables */
.button {
  background-color: var(--primary-color);
  padding: var(--spacing);
  border-radius: var(--border-radius);
}

/* Scoped variables */
.dark-theme {
  --primary-color: #1a1a1a;
  --text-color: #ffffff;
}