dark mode toggle
Dark Mode Toggle: Build One That Remembers and Respects Settings
Build a dark mode toggle that follows the system setting, remembers the visitor's choice, avoids flashes and passes contrast. Code and a no-code route included.

A good dark mode toggle does three things. It follows the visitor’s system setting by default, it lets them override that setting with one control, and it remembers the choice on the next page load without a flash of the wrong theme. You can write that in a few dozen lines of CSS and JavaScript, or you can describe it to your AI assistant and let it build the code into your site.
This guide gives you both routes. You get the working code, the reasons behind each line, the accessibility checks that matter, and how it fits into a site or app built with the AI web platform. WebsitePublisher is full-stack, so your AI assistant builds and publishes the front end and the backend together.
TL;DR
- Set
color-scheme: light darkon the root element so the site follows the system setting with no JavaScript at all. - Use three states: system (nothing stored), light and dark. Store only explicit choices.
- Put a tiny inline script in the
<head>that reads the stored choice before the page paints. That prevents the flash. - Check contrast in both themes: 4.5:1 for text and 3:1 for UI parts like borders and icons.
- With WebsitePublisher, your AI assistant writes and publishes the toggle for you, and every change is live immediately.
Table of Contents
- What a dark mode toggle actually does
- Step 1: Follow the system setting with CSS only
- Step 2: Add a manual override
- Step 3: Remember the choice and stop the flash
- Step 4: Check accessibility in both themes
- The no-code route: have your AI assistant add it
- Our perspective
- Start building your site or app
- Common mistakes to avoid
- FAQ
- Sources
What a dark mode toggle actually does
Visitors already have a system preference. Their phone or computer tells the browser whether they want a light or dark interface. A toggle lets them override that setting for your site only.
The mechanism is the CSS color-scheme property. According to Chrome’s dark mode toggle guide, the value light dark means follow the system, while light or dark pins one scheme. Colors defined with light-dark(), system colors and native UI such as form controls all key off that property.
That gives you a clean model. The toggle does not repaint your page. It only changes one value, and the CSS does the rest.
Should you even show a toggle?
The same Chrome guide says most sites should follow the system preference by default and not put a persistent toggle in the header. A manual override fits better in a settings surface, since permanent header toggles are mostly seen on developer-facing sites.
Where does that leave you? It depends on the project:
- Portfolio or brochure site: follow the system setting automatically. Add a toggle in the footer if you want one.
- Web app with a settings page or account area: put the three-way choice there.
- Blog or documentation with long reading sessions: a visible toggle is worth the space. Feedback Studios, summarizing Nielsen Norman Group, notes that most readers with normal vision read better in light mode, so dark should not be forced as the default, but the switch should be offered, especially for long reading.
Step 1: Follow the system setting with CSS only
Start with the part that needs no JavaScript. The prefers-color-scheme media feature tells your CSS whether the visitor asked for a light or dark theme. web.dev explains that light means dark text on a light background and dark means light text on a dark background.
Define your colors as variables, then change them inside a media query:
:root {
color-scheme: light dark;
--bg: #ffffff;
--text: #1a1a1a;
--accent: #0b5fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--text: #ececec;
--accent: #8ab4ff;
}
}
body {
background: var(--bg);
color: var(--text);
}
Two details matter here.
First, put color-scheme on :root (the html element), not on body. Chrome’s dark mode guidance warns that setting it only on body can leave scrollbars and the initial canvas background in light mode.
Second, keep the base value at light dark. Chrome’s toggle guide says your CSS must not depend on JavaScript. If the script never runs, the site should still follow the system preference and nothing breaks.
Pick colors for each theme, not an inversion
Dark mode is not light mode with the colors flipped. Pure black backgrounds with pure white text can feel harsh, so the example uses near-black and near-white. Accent colors usually need their own value per theme, because a blue that works on white can look dim or fail contrast on a dark surface. That is why --accent changes above.
If your site has many colors, name them once and reuse them. Our guide to design tokens for web design systems shows how one set of named values can drive every component, which makes a second theme a small change instead of a rewrite.
Step 2: Add a manual override
The media query cannot be overridden from JavaScript. That is why a manual toggle needs a different hook: an attribute on the root element. As the freeCodeCamp tutorial points out, you cannot override a CSS media query from JavaScript, so a class or attribute approach is required for manual switching.
We use a data-theme attribute. Extend the CSS from step 1:
:root[data-theme="light"] {
color-scheme: light;
--bg: #ffffff;
--text: #1a1a1a;
--accent: #0b5fff;
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #121212;
--text: #ececec;
--accent: #8ab4ff;
}
Now the rules are simple:
- No
data-themeattribute: the media query decides. data-theme="light": light, whatever the system says.data-theme="dark": dark, whatever the system says.
This matches the three-state model in Chrome’s guide: System (no stored value, the default), Light and Dark.
The button
<button id="theme-toggle" type="button" aria-label="Theme: system, switch to light">
Theme: system
</button>
const root = document.documentElement;
const button = document.getElementById('theme-toggle');
const order = ['system', 'light', 'dark'];
function currentChoice() {
return root.dataset.theme || 'system';
}
function nextChoice(choice) {
return order[(order.indexOf(choice) + 1) % order.length];
}
function applyChoice(choice) {
if (choice === 'system') {
delete root.dataset.theme;
} else {
root.dataset.theme = choice;
}
try {
if (choice === 'system') {
localStorage.removeItem('theme');
} else {
localStorage.setItem('theme', choice);
}
} catch (e) {}
button.textContent = 'Theme: ' + choice;
button.setAttribute('aria-label', 'Theme: ' + choice + ', switch to ' + nextChoice(choice));
}
button.addEventListener('click', () => {
applyChoice(nextChoice(currentChoice()));
});
applyChoice(currentChoice());
The DOM updates before the storage call. If storage fails, the theme still changes for the current page view. The last line sets the right text and label on load, so a visitor who stored dark does not see “Theme: system” until the first click.
This storage pattern, setting localStorage.theme for explicit choices and calling removeItem to return to the operating system preference, is the one described in the Tailwind CSS dark mode docs.
A two-state button (light and dark) is simpler. It is fine for a small site, but you lose the way back to “follow my system.” The three-state version costs a few extra lines and gives visitors full control.

Mind the label
A toggle that only shows a sun or moon icon is hard to use with a screen reader. Give it an accessible name that says what will happen, such as “Switch to dark mode”, and update it as the state changes. When the button also shows text, start the accessible name with that visible text, as the code above does, so voice-control users can activate it by saying what they see. If you build the toggle as a native <button>, keyboard users get focus and activation for free.
Step 3: Remember the choice and stop the flash
Here is where most quick tutorials fail. If you store the choice in localStorage and apply it at the end of the page, visitors who chose dark see a white flash first. The page paints light, then the script runs, then it turns dark.
The fix is a small inline script in the <head>, before your stylesheet and before any content renders. Tailwind’s docs say the theme script should be added inline in the head to avoid a flash of the wrong theme. They also note the preference could instead be stored server-side and rendered on the server.
<head>
<script>
try {
var saved = localStorage.getItem('theme');
if (saved === 'light' || saved === 'dark') {
document.documentElement.dataset.theme = saved;
}
} catch (e) {}
</script>
<link rel="stylesheet" href="styles.css">
</head>
Rules for this script:
- Inline, not an external file. An external file adds a request and can run too late.
- A plain classic script. Do not add
type="module": module scripts are deferred, so the page can paint before the theme is set. (deferandasyncdo nothing on an inline script, which is one more reason to keep it inline.) - Wrapped in
try/catch. Storage can throw in private browsing modes or sandboxed iframes. - Only read and set the attribute. If nothing is stored, do nothing. The media query handles the system preference, and CSS applies before first paint, so there is no flash.
One more warning from Chrome’s guide: do not use matchMedia to delete the stored value just because the system preference happens to match it. Many operating systems switch schemes automatically by time of day. If you cleared the choice every time it matched, a visitor could never pin a scheme.
React to system changes
If your JavaScript reads window.matchMedia('(prefers-color-scheme: dark)').matches, also listen for its change event. Chrome’s dark mode guide states the system preference can change at any time. When your CSS does the work, as in the code above, you get this behavior for free for visitors in system mode.
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (event) => {
// Only matters if your script draws anything itself,
// such as a canvas or chart colors.
});
Ready-made option
Google Chrome Labs publishes a <dark-mode-toggle> custom element. It follows prefers-color-scheme first and, with the permanent attribute, remembers the last selected mode so visitors can override the system setting for your site. It also supports a switch appearance. The docs recommend loading theme-specific stylesheets with the media attribute so visitors do not download CSS they will not use.
Step 4: Check accessibility in both themes
Dark mode is not automatically more accessible. It helps many people in low light, but some visitors with visual impairments or sensitivities prefer light mode, as ACTUM Digital’s accessibility documentation notes. That is the strongest argument for offering a choice and not forcing dark.
Run this check on every page in both themes:
| What to check | Minimum | Notes |
|---|---|---|
| Body text against its background | 4.5:1 | Large text can use 3:1 under WCAG AA |
| Icons, input borders, focus rings | 3:1 | Applies to UI components and graphical objects |
| Accent and link colors | Same ratios | Pick a separate value for each theme |
| Focus indicator | Visible in both themes | A dark ring on a dark page disappears |
| State shown by color alone | Avoid | Add text, an icon or an underline |
The 4.5:1 and 3:1 figures are stated in the Vanilla Framework accessibility documentation, which also advises checking how colors change across light and dark themes. The WCAG 2.1 success criterion for non-text contrast is the source of the 3:1 rule for components.
Then test the unglamorous parts: images with white backgrounds, embedded forms, charts, shadows and code blocks. They are where dark mode usually breaks. For a full test list, use our website accessibility checklist for developers.
Also confirm the toggle itself works on every page and every screen size. If the control is hidden on mobile, visitors on phones cannot use it. Our guide to building and checking a responsive website with AI covers how to test that.
The no-code route: have your AI assistant add it
You do not have to type the code above. With WebsitePublisher, your AI assistant (ChatGPT, Claude, Gemini, Grok and others) builds and publishes websites and apps through the WebsitePublisher connector. The connector uses MCP, the Model Context Protocol, which is the standard way AI assistants plug into outside tools. See the list of supported AI platforms for the full set.
A prompt that works well:
Add a three-state theme control to my site: system, light and dark. Follow the system setting by default. Store only explicit choices. Read the stored choice in an inline script in the head so there is no flash. Use a near-black background in dark mode and check text contrast is at least 4.5:1.
Your assistant writes the CSS, the script and the button into your pages. Because every change on the AI web platform is live immediately, you can open the site, flip the toggle on your phone and ask for changes right away. There is no separate deploy step.
A few tips for good results:
- Name your colors first. Tell the assistant your brand colors and ask for a dark equivalent of each.
- Ask for both themes on every page. A toggle on the home page that does nothing on the pricing page frustrates visitors.
- Review images and embeds. Ask for a version of your logo that works on dark backgrounds.
- Use the visual browser editor for text and design tweaks. You keep control of content and design without regenerating the page.
One project can hold a whole multi-page site. Our guide to a multi-page website with AI shows how to build every page from one brief, and a shared theme works the same way: define it once, use it everywhere. If you use reusable parts, the component library guide explains how to keep them consistent.
Our perspective
Most dark mode tutorials stop at a button that flips a class. That is the easy 10 percent. The real work is what happens around it: the system default, the stored choice, the flash on load, contrast in both palettes and a toggle that works on every page.
That is also why we built WebsitePublisher as a full-stack AI web platform. Your assistant builds and publishes websites and apps through one connector, onto hosting, auth, forms, email, uploads and data that are already in place. It snaps together from a large catalog of ready-made integrations, so you describe the outcome and skip the glue code. The theme setting is part of the same project as the rest of your site or app.
Project memory and task history stay across sessions and assistants. If you start the theme work in one AI assistant and finish it in another, the context comes with you. And with the visual browser editor, you can adjust content and design later without regenerating the page.
Our advice: follow the system setting, offer the choice where visitors will look for it, and check contrast before you ship. Then ask your AI to build it.
Start building your site or app
If you want a site or app with a theme control that your AI assistant builds and publishes for you, WebsitePublisher is the place to start. You get a full-stack backend with hosting, forms, email, uploads and data already built in, plus a catalog of ready-made integrations your AI assistant can use.

See how the AI web platform works, or check the pricing page for plans, including a free one.
Common mistakes to avoid
- Hardcoding
color-scheme: lightordarkas the base. Keeplight darkso the site still follows the system when JavaScript fails. - Applying the saved theme late. A script at the bottom of the page causes the flash.
- Storing “system” as a value. Store nothing for system. An absent value means follow the system.
- Forgetting native controls. Without
color-schemeon the root, scrollbars and form fields can stay light. - Reusing light-mode accents. Check every accent color on the dark background.
- Shipping a toggle only on the home page. Visitors expect their choice to apply everywhere.
FAQ
Should a website default to dark mode?
No. Default to the visitor’s system setting. Most readers with normal vision read better in light mode, according to the Nielsen Norman Group view summarized by Feedback Studios, so forcing dark is a poor default. Offer dark as a choice and let the system preference decide the starting point.
How do I detect a visitor’s dark mode preference?
In CSS, use @media (prefers-color-scheme: dark). In JavaScript, read window.matchMedia('(prefers-color-scheme: dark)').matches and listen for its change event. CSS alone is enough for automatic dark mode. You only need JavaScript for a manual toggle.
How do I make the toggle remember the choice?
Save the choice in localStorage when a visitor picks light or dark, and remove it when they pick system. Then read it in a small inline script in the <head> so the right theme applies before the page paints. Wrap the storage calls in try/catch in case storage is blocked.
Can I add a dark mode toggle without writing code?
Yes. With WebsitePublisher, you describe the toggle to your AI assistant, and it builds and publishes it through the WebsitePublisher connector. The change is live immediately, so you can test it on your own devices and ask for adjustments in the same conversation.
Sources
- Chrome for Developers: dark mode toggle guide
- Chrome for Developers: dark mode guidance
- web.dev: prefers-color-scheme
- Tailwind CSS: dark mode
- freeCodeCamp: how to handle dark mode with CSS and JavaScript
- Chrome Labs: dark-mode-toggle element
- Feedback Studios: dark mode on a website
- ACTUM Digital Accessibility: color mode
- Vanilla documentation: accessibility
Recommended
Build your site the same way
Describe what you want. Your AI builds and publishes it — with the full stack behind it: data, auth, forms, payments, integrations and hosting.
See how it works →
Website