Custom Property Theme Light Dark

Implement a theming system using CSS custom properties with light and dark variants toggled by a data attribute.

CssConfig Management

Code

csssnippet
21 lines
:root {
  --color-bg: #ffffff;
  --color-fg: #1a1a1a;
  --color-accent: #0066cc;
  --spacing-unit: 8px;
  --radius: 6px;
}

[data-theme="dark"] {
  --color-bg: #1a1a1a;
  --color-fg: #f0f0f0;
  --color-accent: #66b3ff;
}

.card {
  background: var(--color-bg);
  color: var(--color-fg);
  border: 1px solid var(--color-accent);
  border-radius: var(--radius);
  padding: calc(var(--spacing-unit) * 2);
}

How the snippet works

Values that repeat across rules live in custom properties (--color-bg, --color-fg, --color-accent, --spacing-unit, --radius), so a theme change is one edit instead of a hunt through every rule.

The rules target :root — each selector names the element it restyles, in source order.

Interactive Tools for This Topic

FAQ

Which elements does this stylesheet target?
The rules bind to `:root`; when two rules tie in specificity, the one written later in the file wins.