In this guide
How to Add Dark Mode to a Website: CSS Variables, System Preference and a Toggle That Remembers
Most visitors now expect a website to offer a dark theme, and many have their operating system set to dark permanently. A good dark mode is not a second stylesheet bolted on at the end. It is a single set of colour tokens that switch together, a default that follows the system, and a toggle that remembers the visitor's choice. Done this way, dark mode is about forty lines of CSS, twenty lines of JavaScript, and no duplicated styles.
The problem with the naive approaches
The two approaches students usually reach for first both cause trouble later. Hard-coding a second stylesheet means every colour change has to be made twice, and the two files drift apart within a week. Swapping classes on dozens of individual elements means the theme logic leaks into every component, and one missed element glows white in the middle of a dark page.
CSS custom properties (variables) solve both problems. Every colour in the site is defined once, in one place. Switching theme means changing the values of those variables, and every element that uses them updates automatically. The rest of the stylesheet never mentions light or dark at all.
How dark mode works in three layers
A solid implementation has three layers, in this order:
- Colour tokens. All colours live in CSS variables on
:root, with a dark set on[data-theme="dark"]. - A default. If the visitor has never chosen, follow the operating system through
prefers-color-scheme. - A remembered choice. A toggle writes the visitor's choice to
localStorage, and that choice wins over the system default on every later visit.
Get the order right: stored choice first, system preference second, light as the fallback. Most bugs in student dark modes come from getting this priority wrong, or from applying the theme after the page has already painted.
Step 1: define your colours as tokens
Start by listing every colour your site actually uses, then give each one a semantic name — what it is for, not what it looks like. --surface and --text are semantic; --light-grey is not, because it stops making sense in dark mode.
:root {
--bg: #ffffff;
--surface: #f4f5f7;
--text: #1a1d21;
--muted: #5b6470;
--border: #d9dde3;
--accent: #1a56db;
--accent-text: #ffffff;
}
body {
background: var(--bg);
color: var(--text);
}
.card {
background: var(--surface);
border: 1px solid var(--border);
}
The discipline that matters here: after this step, no colour value should appear anywhere else in your stylesheet. If you find a hard-coded #fff in a component, move it into a token. A quick search for # in your CSS file tells you how far you have to go.
Step 2: add the dark values
The dark theme is a second block that redefines the same variables. Nothing else changes.
[data-theme="dark"] {
--bg: #121417;
--surface: #1d2025;
--text: #e8eaed;
--muted: #9aa3af;
--border: #33383f;
--accent: #7aa5ff;
--accent-text: #0b1220;
}
A few things worth noting. Pure black (#000) backgrounds look harsh and make text harder to read; a very dark grey like #121417 is easier on the eyes. Pure white text on a dark background has the same problem — #e8eaed is softer. And accent colours almost always need to change: a blue that is readable on white is often too dark on a dark background, so lighten it. Finally, notice --accent-text flips too — the text sitting on the accent colour needs to stay readable in both themes.
Step 3: follow the system preference by default
When a visitor arrives for the first time, the polite default is whatever their operating system already uses. The prefers-color-scheme media query reads that setting:
@media (prefers-color-scheme: dark) {
:root:not([data-theme]) {
--bg: #121417;
--surface: #1d2025;
--text: #e8eaed;
--muted: #9aa3af;
--border: #33383f;
--accent: #7aa5ff;
--accent-text: #0b1220;
}
}
The :not([data-theme]) part is the key detail: the system preference only applies when no explicit choice has been stored yet. Once the visitor picks a theme with the toggle, their choice wins. Without that guard, the media query would fight the toggle every time the page loads.
A cleaner alternative is to keep the dark values in exactly one place — the [data-theme="dark"] block — and let a tiny script set data-theme="dark" on the document when the system prefers dark and no choice is stored. That avoids duplicating the colour values in the media query. Either approach works; the duplicated-values version above is easier to read, and the script version is easier to maintain. Pick one and be consistent.
Step 4: a toggle that remembers
The toggle is a button that flips the data-theme attribute on the <html> element and stores the result:
<button id="theme-toggle" type="button" aria-label="Switch theme">
Switch theme
</button>
var toggle = document.getElementById('theme-toggle');
var stored = null;
try {
stored = localStorage.getItem('theme');
} catch (e) {
stored = null;
}
if (stored === 'dark' || stored === 'light') {
document.documentElement.setAttribute('data-theme', stored);
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.setAttribute('data-theme', 'dark');
}
toggle.addEventListener('click', function () {
var current = document.documentElement.getAttribute('data-theme');
var next = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
try {
localStorage.setItem('theme', next);
} catch (e) {
// Private browsing can block storage; the toggle still works for this visit.
}
});
Two details deserve attention. First, the try...catch around localStorage: some browsers block storage in private mode, and a thrown error there would kill the whole script. Second, the stored value is validated before use — if anything else is in storage, it is ignored and the system preference applies.
For the button itself, a sun/moon icon (an inline SVG, not an emoji) is the usual pattern, and aria-label keeps it usable with a screen reader. A text label such as "Dark" / "Light" is perfectly fine for a student project and clearer than an icon alone.
Step 5: stop the flash of the wrong theme
If the theme script runs at the end of the body, the browser paints the page in the default theme first, then flips it — a visible flash of white for dark-mode visitors. The fix is to run the theme decision before the first paint, with a small inline script element placed in the head of the document, containing only this code:
(function () {
var stored = null;
try { stored = localStorage.getItem('theme'); } catch (e) {}
var theme = stored;
if (theme !== 'dark' && theme !== 'light') {
theme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark' : 'light';
}
document.documentElement.setAttribute('data-theme', theme);
})();
Because this script runs before the stylesheet is applied, the first paint already uses the right colours. Keep this script tiny and dependency-free — it must not wait for anything else. The toggle code from step 4 can stay at the end of the body; it only needs to run when the button is clicked.
Handling images, borders and embedded content
Colours are the easy part. The things students forget:
- Images with white backgrounds. A logo or diagram saved with a white background becomes a glowing rectangle in dark mode. Use transparent PNGs or SVGs for logos, and give diagrams a background that matches
--surface. - Shadows. A dark drop shadow is invisible on a dark background. Reduce shadow opacity in dark mode, or drop shadows entirely and rely on borders.
- Borders. A
#dddborder that is subtle on white disappears on dark grey. Borders usually need to be lighter in dark mode, not darker. - Form controls. Native inputs, selects and scrollbars follow the browser's own theme unless you tell it otherwise. Add
color-scheme: light dark;to:rootso the browser renders its controls to match, and setcolor-scheme: dark;under[data-theme="dark"]if you manage themes manually. - Embedded content. A YouTube iframe or a code widget has its own colours and will not follow your variables. Check each embed in both themes and accept the ones you cannot control — or pick embeds that offer their own dark option.
- Code blocks. Syntax highlighting themes are usually light or dark, not both. If your site shows code, pick a highlighting theme that works on your dark surface, or swap the highlighting stylesheet with the theme.
Testing checklist
Run through this before you call the feature done:
- Toggle switches every page, and the choice survives a reload and a new tab.
- A fresh browser profile with the OS set to dark loads dark first time, with no white flash.
- A fresh profile with the OS set to light loads light first time.
- Every page is checked in both themes: home, a long article, a form, and any page with images or tables.
- Text contrast passes in both themes — body text, muted text, links, and button text.
- No hard-coded colour values remain in the stylesheet (search for
#outside the token blocks). - The toggle is reachable by keyboard and announces itself to a screen reader.
- Print styles still work — a dark background printing as a solid black page is a common surprise; add a
@media printrule that forces light colours.
A quick way to catch missed elements is to screenshot the same page in both themes and compare them side by side. Anything that did not change colour is a hard-coded value you missed.
Frequently asked questions
Should I use a class or a data attribute for the theme?
Either works. A data attribute like data-theme="dark" is slightly clearer to read in the CSS and avoids clashing with utility classes. The important thing is that the whole theme hangs off one attribute on the root element.
Does dark mode need JavaScript at all?
No, if you only want to follow the system preference — the media query alone does that. JavaScript is only needed for the toggle and for remembering the choice. A site with no toggle is a valid, simpler design.
Can I animate the switch between themes?
Yes — add transition: background-color 0.2s, color 0.2s; to the elements that change colour. Keep it short (0.2s or less) and respect prefers-reduced-motion: disable the transition for users who have asked for reduced motion.
How many themes should I offer?
Two is enough for almost every student project. A third "system" option in the toggle (light / dark / follow system) is a nice touch, but it adds a third state to manage and test. Add it only after light and dark both work cleanly.
Does dark mode save battery?
On OLED screens, noticeably; on LCD screens, barely at all. Do not sell dark mode as a battery feature — its real value is comfort and matching what the visitor already prefers.
Limitations
- CSS variables do not reach inside cross-origin iframes, so embedded widgets keep their own theme.
prefers-color-schemereflects the operating system setting; a visitor who wants your site dark while their OS is light still needs the toggle.- Very old browsers do not support CSS custom properties. That is a non-issue for a student project in 2026, but a site that must support legacy browsers needs a different technique.
- A toggle stored in
localStorageis per browser and per device — a choice made on a phone does not carry to a laptop.
Where to go from here
- Storing the choice is only one use of browser storage: Cookies vs localStorage vs sessionStorage: Where Should a Web App Keep Its Data?
- The toggle is a small piece of front-end behaviour; the same care with defaults applies to API calls: CORS Explained: Why Your Frontend API Calls Get Blocked (and How to Fix It)
- When your site grows into a real deployment, the same theme files ship with it: Nginx Reverse Proxy: Host Multiple Apps on One VPS
- More web topics in the Web Development branch hub.