Code snippets
Dark Mode With CSS Variables: A Practical Guide
Define your colours once as CSS custom properties on :root, override them inside a prefers-color-scheme: dark query, and let a data-theme attribute on the html element take priority when the visitor picks a theme manually. A tiny inline script in the head applies the saved choice before the first paint so the page never flashes the wrong theme.
By CodingMarble · Published · 4 min read

Start with colour tokens on :root
Dark mode becomes easy when no component hard-codes a colour. Instead of writing background: #ffffff in forty places, define named values once and refer to them everywhere. CSS custom properties, which you declare with a double-dash name and read with var(), cascade and inherit like any other property, so changing them in one place re-themes everything beneath.
Name tokens by role, not by appearance. A name like --surface describes what the colour is for and stays correct in both themes. A name like --white would be wrong the moment dark mode turns it near-black. Keep the set small and resist adding a new token for every one-off colour, since each extra name is another value that needs a dark counterpart. A page background, a raised surface, text, muted text, a border, and an accent are enough for most sites.
:root {
color-scheme: light;
--bg: #ffffff;
--surface: #f3f4f6;
--text: #111827;
--text-muted: #4b5563;
--border: #d1d5db;
--accent: #1d4ed8;
--accent-text: #ffffff;
}
body {
background: var(--bg);
color: var(--text);
}
.card {
background: var(--surface);
border: 1px solid var(--border);
}
.btn {
background: var(--accent);
color: var(--accent-text);
}The color-scheme property tells the browser which themes the page supports so it can adjust built-in UI to match: form controls, scrollbars and the default canvas colour. Without it, a dark page can still show a bright native scrollbar or white form fields.
Follow the visitor's system setting
The prefers-color-scheme media query reports whether the operating system or browser is set to light or dark. Redefine the tokens inside it and every component updates, because the components already read the tokens.
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--bg: #0f172a;
--surface: #1e293b;
--text: #f1f5f9;
--text-muted: #cbd5e1;
--border: #475569;
--accent: #60a5fa;
--accent-text: #0f172a;
}
}Notice that the dark palette is not a simple inversion. Pure black backgrounds with pure white text produce harsh contrast that many people find tiring to read, so softer dark blues and off-white text are common choices. The accent is lighter than in the light theme because a dark blue on a dark surface would be hard to see, and the text on the accent flips to dark to keep the button readable.
Add a manual toggle with data-theme
Many visitors want to override the system setting for one site. The common pattern is a data-theme attribute on the html element. Because an attribute selector with :root is more specific than :root alone, it overrides the defaults. Dark tokens now need to exist in two places: the media query, for people who have not chosen, and the attribute, for people who have.
To avoid duplicating the dark values, define them once on the attribute and have the media query apply only when no explicit light choice was made.
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #0f172a;
--surface: #1e293b;
--text: #f1f5f9;
--text-muted: #cbd5e1;
--border: #475569;
--accent: #60a5fa;
--accent-text: #0f172a;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
color-scheme: dark;
--bg: #0f172a;
--surface: #1e293b;
--text: #f1f5f9;
--text-muted: #cbd5e1;
--border: #475569;
--accent: #60a5fa;
--accent-text: #0f172a;
}
}CSS cannot share declarations between a media query and a selector without a preprocessor, so a small duplication is the price of this approach. If that bothers you, generate both blocks from one source in your build step. With the CSS in place, a button toggles the attribute and saves the choice.
<button type="button" id="theme-toggle" aria-pressed="false">
Dark mode
</button>
<script>
(function () {
var root = document.documentElement;
var button = document.getElementById("theme-toggle");
function isDark() {
var saved = root.getAttribute("data-theme");
if (saved) return saved === "dark";
return window.matchMedia("(prefers-color-scheme: dark)").matches;
}
button.setAttribute("aria-pressed", String(isDark()));
button.addEventListener("click", function () {
var next = isDark() ? "light" : "dark";
root.setAttribute("data-theme", next);
button.setAttribute("aria-pressed", String(next === "dark"));
try { localStorage.setItem("theme", next); } catch (e) {}
});
})();
</script>The button uses aria-pressed because it is a two-state toggle, and its label stays constant so the meaning does not flip with the state. The try and catch around localStorage matters, since storage can throw in private browsing or when a user has blocked site data. The page should still work when saving fails.
Avoid the flash of the wrong theme
If the saved theme is read by a script at the end of the page, the browser paints the default theme first and then switches, which shows as a visible flash for returning visitors. The fix is a tiny script in the head that sets the attribute before the body is rendered. It must be synchronous and small, so it blocks nothing meaningful.
<script>
try {
var saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.setAttribute("data-theme", saved);
}
} catch (e) {}
</script>
<link rel="stylesheet" href="/styles.css">It reads the saved value, validates it against the two allowed strings so a tampered value does nothing, and sets the attribute on the root element, which already exists at that point. If nothing is saved, the attribute is left off and the media query handles the system preference with no script involved. If your site has a strict Content Security Policy, you will need a nonce or hash to allow this inline script.
Images, shadows and other details
Colours are only part of the work. Bright images on a dark page can glare, and shadows that look natural on white barely register on a dark surface. A few small rules cover most of it.
:root {
--shadow: 0 2px 8px rgb(0 0 0 / 0.12);
}
:root[data-theme="dark"] {
--shadow: 0 2px 8px rgb(0 0 0 / 0.5);
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--shadow: 0 2px 8px rgb(0 0 0 / 0.5);
}
}
.card { box-shadow: var(--shadow); }
:root[data-theme="dark"] img:not([src$=".svg"]) {
filter: brightness(0.9);
}- Shadows: make them stronger in dark mode, or use a slightly lighter surface and a visible border to show elevation instead.
- Logos and icons: SVGs that use currentColor follow the text colour automatically. Raster logos with dark text may need a separate light version, swapped with a picture element and a prefers-color-scheme media attribute.
- Transitions: avoid animating every colour on theme switch. If you add a short colour transition, respect prefers-reduced-motion.
- Third-party widgets such as embeds and maps often ignore your tokens, so test them in both themes.
Test contrast in both themes
Each theme needs checking on its own, because a pairing that passes in light mode can fail in dark. Normal body text should reach a contrast ratio of 4.5:1 against its background under WCAG, large text needs 3:1, and meaningful interface boundaries and focus rings also need 3:1. Test text, muted text, links, borders, placeholder text and disabled states, not only the headline colours.
Your browser's developer tools can show the contrast ratio of a selected element, and you can emulate the system preference from the rendering panel without changing your operating system. Toggle the attribute by hand as well, to confirm the override path works. Record the results next to your tokens so the next person who edits a colour knows which pairings were checked. Finally, try the page with the saved theme cleared, with a saved light choice on a dark system, and with a saved dark choice on a light system, since those three cases are where theme bugs usually hide.
Keep reading
- Code snippetsCSS Button Hover Effects: Fill Slide, Press and FocusA good CSS button has distinct hover, focus-visible, active and disabled states, each changing only cheap properties like background, transform and box-shadow. Build the base button first, add a pseudo-element for the fill-slide hover, wrap hover in a media query for devices that can hover, and never remove the focus ring without replacing it.
- Web developmentResponsive Web Design Checklist for Real SitesA responsive site adapts to any screen width without horizontal scrolling, tiny text or unreachable buttons. Work through the viewport tag, fluid layout, breakpoints set by content, touch sizes, images, tables, forms and real-device testing, and check each one in your own pages.
- Code snippetsFlexbox vs Grid: When to Use Each, With ExamplesUse Flexbox when you are arranging items along one axis, such as a nav bar or a row of buttons, and use Grid when you need to control rows and columns together, such as a page layout or a card gallery. They work well side by side: Grid for the page and card structure, Flexbox for the content inside each cell.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.