SyntaxStudy
Sign Up
css

How to Create a CSS Dark Mode Toggle

Implement a dark/light mode toggle using CSS custom properties and a checkbox.

Dark mode is a must-have for modern web apps. CSS custom properties (variables) make it simple to manage two color schemes.

Approach

  1. Define light mode colors as CSS variables on :root.
  2. Override them inside a .dark class or [data-theme="dark"] attribute.
  3. Use JavaScript to toggle the class on <body>.
  4. Save the preference to localStorage.

System Preference

Respect the user's OS preference with @media (prefers-color-scheme: dark).

Example
:root {
  --bg: #ffffff;
  --text: #1f2937;
  --surface: #f9fafb;
  --border: #e5e7eb;
}

.dark {
  --bg: #0f172a;
  --text: #f1f5f9;
  --surface: #1e293b;
  --border: #334155;
}

body {
  background: var(--bg);
  color: var(--text);
  transition: background 0.3s, color 0.3s;
}