CSSmediumCSS

CSS Dark Mode Variables

Set up CSS custom properties for easy dark/light mode switching.

01

The problem

You need to implement dark and light mode with easy theme switching.

02

The solution

CSS
:root {
  /* Light mode (default) */
  --bg-primary: #ffffff;
  --bg-secondary: #f5f5f5;
  --text-primary: #1a1a1a;
  --text-secondary: #666666;
  --accent: #3a7bff;
  --border: #e0e0e0;
  --shadow: rgba(0, 0, 0, 0.1);
}

[data-theme="dark"] {
  --bg-primary: #0d1126;
  --bg-secondary: #1a1a2e;
  --text-primary: #ffffff;
  --text-secondary: #a0a0a0;
  --accent: #3a7bff;
  --border: #2a2a4e;
  --shadow: rgba(0, 0, 0, 0.3);
}

/* Auto dark mode based on system preference */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg-primary: #0d1126;
    --bg-secondary: #1a1a2e;
    --text-primary: #ffffff;
    --text-secondary: #a0a0a0;
    --border: #2a2a4e;
    --shadow: rgba(0, 0, 0, 0.3);
  }
}

/* Usage */
body {
  background: var(--bg-primary);
  color: var(--text-primary);
}

.card {
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  box-shadow: 0 4px 12px var(--shadow);
}

03

See it live

Isolated previewSandboxed
04

Put it to work

Example
<!-- Toggle theme with JavaScript -->
<button onclick="toggleTheme()">Toggle Theme</button>

<script>
function toggleTheme() {
  const current = document.documentElement.getAttribute('data-theme');
  const next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  localStorage.setItem('theme', next);
}
</script>

Worth knowing

Store theme preference in localStorage. Use prefers-color-scheme for automatic detection.