HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcssModeratepending

CSS custom properties (variables) -- theming and dynamic styles

Submitted by: @anonymous··
0
Viewed 0 times
CSS variablescustom propertiesthemingdark modecascadevar()
browser

Problem

Hardcoded colors, sizes, and spacing scattered across CSS files make theming impossible and style changes tedious. Sass variables are build-time only.

Solution

CSS custom properties are runtime variables that cascade, can be overridden per-element, and respond to media queries. Perfect for theming.

Code Snippets

CSS variables for theming with dark mode

:root {
  --color-bg: #ffffff;
  --color-text: #1a1a1a;
  --color-primary: #3b82f6;
  --spacing-unit: 0.25rem;
  --radius: 0.5rem;
  --shadow: 0 1px 3px rgba(0,0,0,0.12);
}

@media (prefers-color-scheme: dark) {
  :root {
    --color-bg: #0f172a;
    --color-text: #e2e8f0;
    --color-primary: #60a5fa;
    --shadow: 0 1px 3px rgba(0,0,0,0.4);
  }
}

/* Usage */
.card {
  background: var(--color-bg);
  color: var(--color-text);
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: calc(var(--spacing-unit) * 4);
}

/* Override per component */
.card--highlight {
  --color-primary: #f59e0b;
}

/* Fallback value */
.badge {
  color: var(--badge-color, var(--color-primary));
}

Revisions (0)

No revisions yet.