Theming & dark mode
Support light and dark themes with CSS variables.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
Theming stores colors in CSS variables and swaps their values per theme. Respect the user's system preference by default, and let them override it with a toggle that is remembered.
Explained simply
Many people set their phone or laptop to dark mode, especially at night. A good website notices this and switches to dark colors by itself. It should also let people pick light or dark by hand, and remember that choice next time.
The trick is to never write a color directly in a component. Instead, components use named colors like background and text. Those names are CSS variables. In light mode, background means white; in dark mode, the same name means almost black. Swap the values and the whole app changes at once.
The browser tells you the system setting through a media query called prefers-color-scheme. Your saved choice, if any, wins over it. That choice is usually stored in localStorage or a cookie.
The tricky part is timing. If your page first paints in light mode and then a script switches it to dark, users see an ugly white flash. The fix is a tiny script that sets the theme before the first paint.
Press Play on a diagram to walk through it one step at a time.
- Step 1Saved choice?
Read the user's stored theme, if any
- Step 2System preference
Otherwise use prefers-color-scheme
- Step 3Set data-theme
Put the theme on the html element
- Step 4Variables switch
CSS variables change, every component updates
- 1User's saved choice
light or dark in localStorage or a cookie
- 2System preference
prefers-color-scheme from the OS
- 3Site default
Usually light, used when nothing else is known
In depth
Designing dark colors, not just inverting
Dark mode is not light mode with the colors flipped. Pure black backgrounds with pure white text cause glare and halos for many readers, so most designs use a dark grey or navy background and slightly softened text. Elevated surfaces like cards and menus get a little lighter than the page, because shadows barely show on dark backgrounds.
Saturated brand colors often look too bright on dark, so you may need a lighter, less intense version. Check contrast for both themes: at least 4.5:1 for normal text. Images and illustrations may need their own versions, and you can use the picture element with a media attribute to serve a dark image.
- Use dark grey (for example #0b0f19) rather than #000
- Raise surfaces with lighter fills instead of shadows
- Re-check contrast in both themes
Telling the browser about your theme
The CSS property color-scheme tells the browser which themes your page supports. Set color-scheme: light dark on :root and native parts like form controls, scrollbars and the default canvas follow the active theme. When the user forces a theme, set color-scheme: dark on that theme's selector too, or native inputs stay light.
Modern CSS also has a light-dark() function: color: light-dark(#111, #eee) picks the first value in light scheme and the second in dark, based on color-scheme. It is supported in all major browsers since 2024. In JavaScript, window.matchMedia("(prefers-color-scheme: dark)") reads the setting, and its change event fires when the user flips their system theme.
- :root { color-scheme: light dark; }
- [data-theme="dark"] { color-scheme: dark; }
- light-dark(a, b) needs color-scheme to be set
Avoiding the flash on first paint
In a server-rendered app, the server does not know what is in the browser's localStorage. So the HTML arrives without the user's choice. If React applies the theme after hydration, the page has already painted in the wrong colors.
There are two good fixes. One: a small inline script in the head reads localStorage and sets data-theme on the html element before the body paints. Because the server HTML and the browser DOM now differ on that one attribute, add suppressHydrationWarning to the html tag. The next-themes library does exactly this for you. Two: store the choice in a cookie, read it on the server with cookies(), and render the right data-theme straight into the HTML. The cookie way makes the route dynamic, so it costs static caching.
- Server to Browser: HTML with no theme attribute1HTML with no theme attribute
- Browser to Inline head script: Runs before body paints2Runs before body paints
- Inline head script to Browser: Reads localStorage, sets data-theme=dark3Reads localStorage, sets data-theme=dark
- Browser to React: Paints dark, then loads JS4Paints dark, then loads JS
- React to Browser: Hydrates; toggle shows Dark5Hydrates; toggle shows Dark
Wiring Tailwind's dark variant to your toggle
By default, Tailwind's dark: variant follows prefers-color-scheme, so dark:bg-gray-900 works with no setup. Once you add a manual toggle, you need dark: to follow your attribute instead. In Tailwind v4, add one line to your CSS: @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)). Now dark: applies inside any element with data-theme="dark".
A cleaner approach for big apps is to rarely use dark: at all. Define semantic colors such as --color-bg and --color-fg in @theme, then redefine those variables under [data-theme=dark]. Components just use bg-bg and text-fg and never think about themes. Save dark: for the odd exception, like a logo that needs a different shade.
- @custom-variant dark (&:where(.dark, .dark *)); for a class toggle
- Prefer semantic variables over many dark: classes
- A three-way toggle: light, dark, system
Learn it in 3 short steps
About 30m each. Track them with a timer in your plan.
- 1Define theme colors as CSS variables~30m
- 2Respect prefers-color-scheme~30m
- 3Add a persisted theme toggle~30m
Key points
- Define colors once as CSS variables and redefine them for dark mode.
- prefers-color-scheme reads the operating system's light or dark setting.
- Apply the saved theme before first paint to avoid a flash of the wrong theme.
- Check contrast in both themes, not just light.
Key terms
Tap a card to flip it. 0/4 known
Examples
:root { --bg: #ffffff; --text: #111827; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) { --bg: #0b0f19; --text: #e5e7eb; }
}
:root[data-theme='dark'] { --bg: #0b0f19; --text: #e5e7eb; }
body {
background: var(--bg);
color: var(--text);
}System preference by default, with a manual override.
A three-way theme toggle
You want Light, Dark and System options. Step 1: store the choice as "light", "dark" or "system" in localStorage. Step 2: to apply it, if the choice is system, read matchMedia; otherwise use the choice. Step 3: set data-theme on document.documentElement. Step 4: while on system, listen for the media query change event so the page follows the OS live. Wrap localStorage in try and catch, because it can throw in private modes.
type Choice = "light" | "dark" | "system";
const mq = window.matchMedia("(prefers-color-scheme: dark)");
export function applyTheme(choice: Choice) {
const dark = choice === "dark" || (choice === "system" && mq.matches);
document.documentElement.dataset.theme = dark ? "dark" : "light";
try { localStorage.setItem("theme", choice); } catch {}
}
mq.addEventListener("change", () => {
let saved: string | null = null;
try { saved = localStorage.getItem("theme"); } catch {}
if (!saved || saved === "system") applyTheme("system");
});No flash in the Next.js root layout
Step 1: in app/layout.tsx, add a tiny script string that runs before paint and sets data-theme. Step 2: render it with dangerouslySetInnerHTML inside head, so it runs synchronously. Step 3: add suppressHydrationWarning to the html tag, because the attribute differs from the server HTML. Step 4: reload with dark saved and confirm there is no white flash, even with network throttling on.
const themeScript = `try{var t=localStorage.getItem('theme');
var d=t==='dark'||((!t||t==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.dataset.theme=d?'dark':'light'}catch(e){}`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body>{children}</body>
</html>
);
}Quick reference
- @media (prefers-color-scheme: dark) { ... } follows the OS setting
- :root { color-scheme: light dark; } makes form controls and scrollbars match
- color: light-dark(#111, #eee) picks a value by the active color scheme
- matchMedia("(prefers-color-scheme: dark)").matches reads the setting in JS
- Set the theme in an inline head script to avoid a flash of the wrong theme
- Add suppressHydrationWarning on html when a script changes its attributes
- Tailwind v4: @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
Common mistakes
- Hard-coding colors in components, so they ignore the theme.
- Reading localStorage after render and flashing the wrong theme.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Define --bg and --fg for light mode, redefine them for prefers-color-scheme dark, and apply them to body.
- Exercise 2medium
Extend the easy solution so a data-theme attribute on html can force light or dark, whatever the system says.
- Exercise 3hard
Build a ThemeToggle client component that cycles light, dark, system, shows the current choice and keeps it after reload without a flash.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use next-themes or write my own?
- next-themes is small, handles the inline script, system changes and syncing across tabs, so it is a good default. Writing your own is fine for learning and takes about 20 lines.
- Is dark mode better for the eyes or the battery?
- It can save battery on OLED screens, where black pixels are off. For reading comfort it depends on the person and the room, which is why letting users choose matters.
- Should I store the theme in localStorage or a cookie?
- localStorage is simplest and keeps pages static. A cookie lets the server render the right theme directly, but reading cookies makes those routes dynamic in Next.js.