Color scheme

Theme Toggle and Storage

This choose topic is different from the others. Every student is adding a theme toggle to their portfolio this week as part of the Tokenized Color System and Dark Mode assignment. That assignment gives you the HTML, CSS, and JavaScript to copy and paste, and it works. But it does not explain why the toggle is built the way it is, what alternatives existed before, or what trade-offs the current approach makes. This page fills that gap. If you choose this topic, your teaching video should help your teammates understand the mechanism they just installed, not just the fact that it works.

A Brief History of Dark Mode on the Web

The idea of letting users switch between light and dark color schemes is not new, but the tools available to implement it have changed dramatically. Understanding where things started makes the current approach feel much less mysterious.

The JavaScript Class Toggle Era

The earliest dark mode implementations were entirely JavaScript-driven. A button would add or remove a class like .dark-mode on the <body> element, and the entire color system was duplicated in CSS under that class:


        /* Light (default) */
        body {
            background: #ffffff;
            color: #1a1a1a;
        }

        /* Dark (toggled by JS) */
        body.dark-mode {
            background: #1a1a1a;
            color: #e0e0e0;
        }

        /* Every component needed a duplicate block */
        .card { background: #f5f5f5; }
        body.dark-mode .card { background: #2a2a2a; }
    

This worked, but it scaled poorly. Every component needed two rule sets. The specificity of body.dark-mode .card was higher than .card, which made overrides tricky. And because JavaScript controlled the toggle, there was a visible flash of the wrong theme on page load (known as FOUC, or Flash of Unstyled Content) while the script ran and applied the class.

The prefers-color-scheme Media Query

In 2019, browsers shipped the prefers-color-scheme media query. For the first time, CSS could detect the user's operating system preference without any JavaScript:


        body {
            background: #ffffff;
            color: #1a1a1a;
        }

        @media (prefers-color-scheme: dark) {
            body {
                background: #1a1a1a;
                color: #e0e0e0;
            }
        }
    

This was a significant improvement. No JavaScript, no FOUC, and the browser handled the detection. But it had a limitation: you could only follow the OS preference. There was no way for the user to override it on your site. If someone preferred dark mode in their OS but wanted your site in light mode, they were out of luck unless you added JavaScript back into the mix.

Custom Properties and the Toggle Hybrid

The next evolution used custom properties as an abstraction layer. Instead of duplicating every rule, developers defined color tokens as custom properties and swapped their values in the media query or under a JavaScript-toggled class:


        :root {
            --bg: #ffffff;
            --text: #1a1a1a;
        }

        :root.dark {
            --bg: #1a1a1a;
            --text: #e0e0e0;
        }

        body { background: var(--bg); color: var(--text); }
        .card { background: var(--bg); }
    

This was much better. Components referenced tokens instead of hardcoded colors, so adding dark mode meant changing the tokens once rather than duplicating every rule. But it still relied on JavaScript to add the .dark class, and the FOUC problem persisted unless you loaded the script in a render-blocking position.

Where We Are Now

The approach you installed this week uses three modern CSS features that eliminate most of the historical pain points: color-scheme, light-dark(), and :has(). Together, they let CSS handle the entire toggle mechanism. JavaScript's only job is saving and restoring the user's preference from localStorage. No class toggling, no duplicate rule sets, no specificity battles.

How the CSS-First Toggle Works

The toggle you added to your portfolio uses a pattern that might have looked unusual when you pasted it in. Here is what each piece does and why it is built that way.

The Hidden Radio Group

Somewhere in your HTML (injected by the JavaScript, which we will cover shortly), there is a hidden <div> containing three radio inputs named theme-preference with values light, system, and dark. The visible toggle in your header is a second set of radio inputs with the same name attribute. Because radio inputs with the same name share state across the entire document, checking one in the visible toggle also unchecks the corresponding one in the hidden group and vice versa. This is native HTML behavior, not JavaScript.

The :has() Selector

The key CSS rules look like this:


        /* Default */
        :root {
            color-scheme: light;
        }
 
        /* User chose dark */
        html:has(input[name='theme-preference'][value='dark']:checked) {
            color-scheme: dark;
        }
 
        /* User chose system and OS prefers dark */
        @media (prefers-color-scheme: dark) {
            html:has(input[name='theme-preference'][value='system']:checked) {
                color-scheme: dark;
            }
        }
    

The :has() selector lets html match based on the state of a descendant element. When the dark radio is checked, html gets color-scheme: dark. When the system radio is checked and the OS preference is dark, the nested media query flips it. In every other case, the default color-scheme: light applies.

The light-dark() Function

Once color-scheme is set, every light-dark() call in your tokens resolves automatically. When the computed color-scheme is light, the first value wins. When it is dark, the second value wins. No JavaScript, no class toggling, no media query duplication:


        --color-bg: light-dark(var(--seed-bg), oklch(0.18 0.02 260));
    

This single declaration handles both modes. The browser resolves the correct value based on the current color-scheme at paint time.

What the JavaScript Actually Does

The CSS handles the toggle itself, but JavaScript has two jobs: restoring the saved preference before the page paints (so there is no theme flash), and saving the preference when the user makes a choice.

The Early Sync Script

The file theme-preference.js runs in the <head> as a render-blocking script. It does not use defer or async because it needs to finish before the browser paints anything. Here is the full script:


        /**
        * Theme preference: restore on load (before paint) and persist on change.
        * Load in <head> WITHOUT defer or async.
        */
        (() => {
            const ALLOWED_VALUES = ['light', 'system', 'dark'];
            const ALLOWED = new Set(ALLOWED_VALUES);
            const syncContainerId = 'theme-preference-sync';
 
            let container = document.getElementById(syncContainerId);
            if (!container) {
                container = document.createElement('div');
                container.id = syncContainerId;
                container.hidden = true;
                container.setAttribute('aria-hidden', 'true');
 
                ALLOWED_VALUES.forEach((v) => {
                    const input = document.createElement('input');
                    input.type = 'radio';
                    input.name = 'theme-preference';
                    input.value = v;
                    if (v === 'system') {
                        input.checked = true;
                    }
                    container.appendChild(input);
                });
 
                const mount = document.body ?? document.head;
                if (mount) {
                    mount.appendChild(container);
                }
            }
 
            let stored = null;
            try {
                stored = localStorage.getItem('theme-preference');
            } catch {
                /* ignore (e.g. disabled storage) */
            }
 
            const value = ALLOWED.has(stored) ? stored : 'system';
            const input = container.querySelector(
                'input[value="' + value + '"]'
            );
            if (input) {
                input.checked = true;
            }

            document.addEventListener('change', (e) => {
                if (e.target.name === 'theme-preference') {
                    try {
                        localStorage.setItem('theme-preference', e.target.value);
                    } catch {
                        /* storage may be disabled */
                    }
                }
            });
        })();
    

Here are the key points to understand:

  • It checks whether the hidden radio group (#theme-preference-sync) already exists in the DOM. If not, it creates one with three radio inputs and appends it. If document.body does not exist yet (because the script is in the <head>), it appends to document.head instead. The :has() selector on html matches either way.
  • It reads the saved preference from localStorage inside a try/catch block. The try/catch is there because localStorage can throw in private browsing modes, embedded iframes, or when the user has disabled storage.
  • It validates the stored value against a Set of allowed strings. If the value is missing, corrupted, or anything unexpected, it defaults to system. This prevents a tampered localStorage value from breaking the toggle.
  • It checks the matching radio input. Because this happens before the first paint, the CSS :has() rules pick up the correct state immediately. No flash.

The Save Listener

The visible toggle in the header also needs a listener that writes the user's choice to localStorage whenever they click an option. This typically lives in your main.js file and listens for change events on the radio inputs inside .theme-menu. When a radio is checked, it writes the value to localStorage under the key theme-preference. The next time any page on the site loads, the early sync script reads that key and restores the choice.

The Emoji Icons

The visible toggle uses three emoji characters as its icons: ☀️ for light, ⚙️ for system, and 🌖 for dark. The summary element also swaps its ::before content to show the current selection. This is a deliberate choice with real trade-offs worth understanding.

Why Emoji Work Here

  • Zero asset loading. No image requests, no icon font, no SVG sprite sheet. The characters are built into every operating system.
  • Universal recognition. A sun, a gear, and a moon are widely understood symbols for light, settings, and dark.
  • Simplicity. The toggle is a small, self-contained component. Adding a full icon system for three symbols would be over-engineering.

Where Emoji Fall Short

  • Inconsistent rendering. Emoji look different on Windows, macOS, Android, and iOS. The 🌖 moon on Windows looks nothing like the same character on macOS. If visual consistency across platforms matters, emoji are unreliable.
  • No CSS control. You cannot change the color of an emoji with color or fill. You can scale them with font-size, but that is the extent of your styling control.
  • Accessibility requires extra markup. Emoji have Unicode names, but those names are often unhelpful for screen readers (the gear emoji announces as "gear" which is fine, but some emoji announce with long, awkward descriptions). The aria-hidden="true" on the emoji span and the visually-hidden span with a readable label is the correct pattern.

The SVG Alternative

If you wanted full control over the icons, inline SVG is the strongest alternative. SVG icons render identically on every platform, can use currentColor to inherit the text color, and can be styled with CSS (stroke width, fill, transitions). A good source for clean, open-source SVG icons is Lucide, which provides a large library of consistent, well-crafted icons designed for web use.

The trade-off is complexity. Three inline SVGs in a toggle component add more markup than three emoji characters, and you need to manage the viewBox, sizing, and accessibility attributes yourself. For a small component like this toggle, emoji are a reasonable choice. For a full design system with dozens of icons, SVG is the better investment.

Resources

Teaching Video Checklist

When you record your teaching video, make sure your teammates come away understanding these concepts:

  • How dark mode was handled before modern CSS (class toggling, duplicated rules, FOUC) and why the current approach is simpler
  • How color-scheme, light-dark(), and :has() work together so that CSS handles the entire toggle without JavaScript class manipulation
  • Why the JavaScript runs render-blocking in the <head> and what would happen if it ran with defer (a flash of the wrong theme)
  • How localStorage persistence works: the early sync script restores the choice, the save listener in main.js writes it
  • The trade-offs of emoji vs. SVG icons for the toggle indicator

For your demo, walk through the toggle on your own portfolio. Open DevTools, show the hidden radio group in the DOM, change the checked value manually, and show how the theme flips. Then clear localStorage, reload, and show what happens when no saved preference exists. Your teammates should leave your video understanding the mechanism they installed, not just the fact that it works.