Frontend Patterns

Pattern

CSS Custom Properties

Use CSS variables for dynamic styling and easy theme customization.

Styling Beginner

CSS Custom Properties

Problem

Design values like colors, spacing, and font sizes are hardcoded throughout stylesheets with magic numbers and repeated values. Changing a brand color or adjusting spacing requires finding and updating dozens of instances across multiple files, often missing some and creating visual inconsistencies.

Solution

Store theme preferences as CSS custom properties at the document root. This lets you update colors, spacing, and typography across your entire application by changing a single variable, and browsers handle the cascade automatically.

Example

This example demonstrates CSS custom properties (variables) to define reusable design values that can be dynamically updated at runtime.

/* Define global design tokens at the root level */
:root {
  --primary-color: #007bff;  /* Brand color used across the application */
  --spacing-unit: 8px;       /* Base spacing unit for consistent layout */
}

/* Reference custom properties using var() function */
.button {
  background: var(--primary-color);           /* Uses the brand color */
  padding: calc(var(--spacing-unit) * 2);     /* 16px padding (8px * 2) */
}

Benefits

  • Enables dynamic theming by updating variables at runtime via JavaScript.
  • Reduces duplication by defining values once and reusing throughout stylesheets.
  • Better for theming than preprocessor variables since they update live.
  • Works with cascade and inheritance unlike preprocessor variables.
  • Supported natively in all modern browsers without build tools.

Tradeoffs

  • Limited support in older browsers like IE11 without polyfills.
  • No computation capabilities like Sass variables have.
  • Can be overused leading to hard-to-trace style issues.
  • Performance impact if too many custom properties are defined.
  • Requires fallback values for browsers without support.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.