Themes with Tailwind and CSS variables without blinking on loading: 8 themes and SSR
Where is the blinking from?
The user selected a dark theme, it is saved in localStorage. When rebooting, the server returns HTML without information about the topic - it does not see localStorage. The browser draws a light page, then JavaScript loads, React hydrates, useEffect reads the setting and switches the class. There is a noticeable flash between the first render and the effect.
To avoid this, the theme must be applied before the first render. There are two ways: a synchronous script in <head> or a cookie that the server reads when rendering.
Variables for eight themes
Each topic is a set of values of the same variables. Components refer only to semantic names (--bg, --fg), not to specific colors:
/* app/themes.css */
:root, [data-theme="light"] {
--bg: #ffffff; --surface: #f6f6f5; --fg: #1b1b1a; --muted: #6e6d68;
--border: #e4e3df; --accent: #2457d6;
color-scheme: light;
}
[data-theme="dark"] {
--bg: #121211; --surface: #1b1b1a; --fg: #ececea; --muted: #a09f99;
--border: #2b2b29; --accent: #6b8ff2;
color-scheme: dark;
}
[data-theme="dracula"] {
--bg: #282a36; --surface: #303241; --fg: #f8f8f2; --muted: #a4a7bd;
--border: #44475a; --accent: #bd93f9;
color-scheme: dark;
}
[data-theme="solarized-light"] {
--bg: #fdf6e3; --surface: #eee8d5; --fg: #073642; --muted: #657b83;
--border: #e0d9c3; --accent: #268bd2;
color-scheme: light;
}
/* ...ещё четыре темы по той же схеме: nord, monokai, github-dark, one-light */color-scheme is important: it switches system elements (scrollbars, native select, field autofill) to the appropriate mode. Without it, light scrollbars will remain on the dark theme.
Connecting to Tailwind v4
In Tailwind v4, the theme is set in CSS. The @theme inline directive creates utilities that reference your variables rather than copying values:
/* app/globals.css */
@import "tailwindcss";
@import "./themes.css";
@theme inline {
--color-bg: var(--bg);
--color-surface: var(--surface);
--color-fg: var(--fg);
--color-muted: var(--muted);
--color-border: var(--border);
--color-accent: var(--accent);
}
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *, [data-theme=dracula], [data-theme=dracula] *));Now bg-bg, text-fg, border-border and transparency modifiers like bg-accent/10 work for all themes at once. The dark: option has been redefined to work on all dark themes; list them all. If dark themes only differ in variables, dark: may not be needed.
For Tailwind v3, the same is done in the config: variables store color channels, and in theme.extend.colors - bg: "rgb(var(--bg) / <alpha-value>)".
Script before rendering
// app/layout.tsx
const THEMES = ["light", "dark", "dracula", "solarized-light", "nord", "monokai", "github-dark", "one-light"];
const themeScript = `(function(){try{
var t = localStorage.getItem("theme");
var allowed = ${JSON.stringify(THEMES)};
if (allowed.indexOf(t) === -1) {
t = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
document.documentElement.setAttribute("data-theme", t);
}catch(e){}})();`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ru" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body className="bg-bg text-fg">{children}</body>
</html>
);
}Key points:
- The script is inline and synchronous, without
async/defer, therefore it is executed before renderingbody. suppressHydrationWarningto<html>: the server rendered the element withoutdata-theme, but the client sees the attribute. Suppression only affects the attributes of this element, not its children.- The value from
localStorageis checked against the list: otherwise a string can be written there that will break the selectors. try/catch, because accessinglocalStoragethrows an exception in some privacy modes.
If the site has a strict CSP, the inline script needs nonce or a hash. The next-themes library does the same and can work with multiple themes via the attribute="data-theme" and the themes list.
Switch
"use client";
export function ThemeSelect({ themes }: { themes: string[] }) {
return (
<select
defaultValue={typeof document !== "undefined" ? document.documentElement.dataset.theme : undefined}
onChange={(e) => {
const t = e.target.value;
const root = document.documentElement;
root.classList.add("no-transitions");
root.dataset.theme = t;
localStorage.setItem("theme", t);
requestAnimationFrame(() => requestAnimationFrame(() => root.classList.remove("no-transitions")));
}}
>
{themes.map((t) => <option key={t} value={t}>{t}</option>)}
</select>
);
}.no-transitions, .no-transitions * { transition: none !important; }The no-transitions class removes ripples when hundreds of elements have their background and border colors animated at the same time.
Option with cookies
If the theme is stored in a cookie, the server can render <html data-theme="..."> straight away and no script is needed. Price - reading cookies() in the root layout makes all pages dynamic, and static generation disappears. For a content site with static content, the script is more profitable, for an application with authorization, where everything is dynamic, the cookie is cleaner.
Diagnostics
- Blinking remains: check in the source HTML (
view-source:) that the script is in<head>before the styles and is not turned into deferred by the builder. - Only some of the elements blink: in some places the colors are set directly (
bg-white,#fff), and not through variables. Search bybg-white|text-black|#fffin components. - Hydration warning on
body:suppressHydrationWarningis on the wrong element, or the theme changes classes tobodyinstead of attribute tohtml.
When eight topics are not needed
Most products have enough light, dark and systemic. Each additional topic is a test of the contrast of all component states. Eight topics are justified where personalization is part of the product: code editors, developer tools, readers.