CSS Academy · Lesson

Automatic and Manual Dark Mode Toggle

Build a theme toggle that respects system preference by default and lets users override it manually.

Lesson 4 of 413 steps

Automatic and Manual Dark Mode Toggle is a free CSS Academy lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the CSS Academy learning path, and your progress syncs across the web and the CoddyKit app. The CSS Academy course includes 4 lessons in total.

The Goal

An ideal dark mode implementation: auto-detects the OS preference by default, and provides a toggle button that lets users override it independently, with the preference persisted across page loads.

Architecture Overview

Three states to handle:

  1. System preference: use prefers-color-scheme with CSS variables
  2. User override: dark: set a class or data attribute on <html>
  3. User override: light: set a different class to prevent auto dark

CSS Token Setup

Define CSS variables that cascade correctly for all states:

<div class="demo" data-theme="dark">Dark token demo</div>
<div class="demo" data-theme="light">Light token demo</div>

JavaScript Toggle Logic

Read saved preference, apply it, and update on toggle:

<div class="demo" id="theme-demo">Toggle my theme</div>
<div class="demo" data-theme="dark">Dark override example</div>
<button id="toggle-btn">Toggle Theme</button>
<script>
  function toggleTheme() {
    const current = document.getElementById('theme-demo').dataset.theme;
    const system = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    if (!current) {
      const next = system === 'dark' ? 'light' : 'dark';
      document.getElementById('theme-demo').dataset.theme = next;
    } else {
      delete document.getElementById('theme-demo').dataset.theme;
    }
  }
  document.getElementById('toggle-btn').addEventListener('click', toggleTheme);
</script>

Three-State Toggle

A more refined three-state toggle: Light | System | Dark:

<div class="demo" id="theme-demo">Cycles: light → system → dark</div>
<div class="demo" data-theme="dark">Dark state example</div>
<p id="state-label">system</p>
<button id="cycle-btn">Cycle Theme</button>
<script>
  const states = ['light', 'system', 'dark'];
  let current = 'system';
  const demo = document.getElementById('theme-demo');
  const label = document.getElementById('state-label');
  document.getElementById('cycle-btn').addEventListener('click', () => {
    current = states[(states.indexOf(current) + 1) % states.length];
    label.textContent = current;
    if (current === 'system') { delete demo.dataset.theme; } else { demo.dataset.theme = current; }
  });
</script>

Preventing Flash of Wrong Theme

Apply the saved theme synchronously before the page renders:

<pre class="code-sample">&lt;!-- In &lt;head&gt;, before any styles --&gt;
&lt;script&gt;
  const t = localStorage.getItem("theme");
  if (t) document.documentElement.dataset.theme = t;
&lt;/script&gt;</pre>

Toggle Button Accessibility

The toggle button should communicate the current state to screen readers. Update the accessible label when toggled:

<button id="theme-toggle" aria-label="Switch to dark mode">🌙</button>

Animated Theme Transition

Smooth color transitions when the theme changes:

<div class="demo" id="at-demo">Smooth theme transition</div>
<button onclick="document.documentElement.classList.add('theme-transitioning'); const d=document.getElementById('at-demo'); const dark = d.style.background==='rgb(17, 17, 17)'; d.style.background = dark ? '#fff' : '#111'; d.style.color = dark ? '#111' : '#fff'; setTimeout(()=>document.documentElement.classList.remove('theme-transitioning'),250);">Toggle</button>

System Change Listening

Also react if the user changes their OS preference while the page is open:

<p id="status">Listening for system theme changes…</p>
<script>
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
    document.getElementById('status').textContent = 'System changed to ' + (e.matches ? 'dark' : 'light');
  });
</script>

Dark Mode Icons

Swap icons for each mode. Use the picture element for theme-aware images, or CSS to show/hide different icons:

<div>Light: <span class="icon-sun">☀️</span><span class="icon-moon">🌙</span></div>
<div data-theme="dark">Dark: <span class="icon-sun">☀️</span><span class="icon-moon">🌙</span></div>

Summary: Implementation Checklist

Dark mode checklist:

  • CSS variables for all color tokens
  • prefers-color-scheme media query for auto detection
  • data-theme attribute for manual override
  • localStorage for persistence
  • Inline script in head to prevent flash
  • Accessible toggle button with dynamic aria-label

Quick Check

What technique prevents a "flash of wrong theme" when the page loads?

Recap

A complete dark mode toggle uses CSS variables for theme tokens, a prefers-color-scheme query for automatic detection, a data-theme attribute for manual override, localStorage for persistence, and a synchronous head script to prevent flashing. Provide an accessible three-state toggle (light/system/dark) for the best user experience.

Free to start

Learn CSS with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Automatic and Manual Dark Mode Toggle” lesson free?

Yes — the full text of “Automatic and Manual Dark Mode Toggle” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the CSS Academy course, upgrade to CoddyKit PRO. The CSS Academy course includes 4 lessons in total.

What will I learn in “Automatic and Manual Dark Mode Toggle”?

Build a theme toggle that respects system preference by default and lets users override it manually. You practise CSS Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start CSS Academy?

No prior experience is required. CSS Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Automatic and Manual Dark Mode Toggle” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this CSS Academy lesson?

Yes. Every CSS Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. prefers-color-scheme Media Query
  2. CSS Variables for Theming
  3. color-scheme Property
  4. Automatic and Manual Dark Mode Toggle
← Back to CSS Academy