Skip to content
CSS3

Custom Properties

Define and reuse CSS variables with live updates.

By EZ4Code Team
custom-propertiesvariables

Code

:root {
  --color-primary: #1976d2;
  --spacing: 8px;
  --radius: 4px;
}

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

/* Override per component or theme */
.dark {
  --color-primary: #90caf9;
}

/* Fallback value if the variable is undefined */
.box {
  color: var(--missing, #333);
}

/* Update at runtime via JS */
// document.documentElement.style.setProperty("--spacing", "12px");

Explanation

Custom properties (CSS variables) store reusable values on the :root or any element and cascade like normal properties. The var() function reads them with an optional fallback. Because they are live, updating a variable via CSS or JS instantly restyles everything that references it.

More CSS3 Snippets