带有 Tailwind 和 CSS 变量的主题,加载时不会闪烁:8 个主题和 SSR
闪烁从哪里来?
用户选择了深色主题,它保存在localStorage中。重新启动时,服务器返回 HTML,但没有有关该主题的信息 - 它看不到 localStorage。浏览器绘制一个轻量级页面,然后加载 JavaScript,React 水合,useEffect 读取设置并切换类。第一次渲染和效果之间有明显的闪光。
为了避免这种情况,必须在第一次渲染之前应用主题。有两种方式:<head>中的同步脚本或服务器在渲染时读取的cookie。
八个主题的变量
每个主题都是一组相同变量的值。组件仅引用语义名称(--bg、--fg),而不引用特定颜色:
/* 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 很重要:它将系统元素(滚动条、本机 select、字段自动填充)切换到适当的模式。如果没有它,浅色滚动条将保留在深色主题上。
连接到 Tailwind v4
在 Tailwind v4 中,主题是在 CSS 中设置的。 @theme inline 指令创建引用变量而不是复制值的实用程序:
/* 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] *));现在,bg-bg、text-fg、border-border 和透明度修改器(如 bg-accent/10)同时适用于所有主题。 dark: 选项已被重新定义以适用于所有深色主题;将它们全部列出。如果深色主题仅在变量上有所不同,则可能不需要 dark:。
对于 Tailwind v3,在配置中执行相同的操作:变量存储颜色通道,以及在 theme.extend.colors - bg: "rgb(var(--bg) / <alpha-value>)" 中。
渲染前的脚本
// 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>
);
}要点:
- 该脚本是内联且同步的,没有
async/defer,因此它在渲染body之前执行。 suppressHydrationWarning到<html>:服务器渲染没有data-theme的元素,但客户端看到该属性。抑制仅影响该元素的属性,而不影响其子元素。- 根据列表检查
localStorage中的值:否则可以在那里写入一个字符串,这会破坏选择器。 try/catch,因为在某些隐私模式下访问localStorage会引发异常。
如果站点有严格的 CSP,则内联脚本需要 nonce 或哈希值。 next-themes 库执行相同的操作,并且可以通过 attribute="data-theme" 和 themes 列表处理多个主题。
切换
"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; }当数百个元素的背景和边框颜色同时进行动画处理时,no-transitions 类会消除波纹。
带 cookie 的选项
如果主题存储在 cookie 中,服务器可以立即渲染 <html data-theme="...">,无需脚本。 Price - 在根布局中读取 cookies() 使所有页面动态化,静态生成消失。对于具有静态内容的内容网站,脚本更有利可图,对于具有授权的应用程序,一切都是动态的,cookie 更干净。
诊断
- 仍然闪烁:在源 HTML (
view-source:) 中检查脚本是否位于样式之前的<head>中,并且未被构建器转为延迟。 - 只有某些元素闪烁:在某些地方,颜色是直接设置的(
bg-white、#fff),而不是通过变量。在组件中按bg-white|text-black|#fff搜索。 body上的水合警告:suppressHydrationWarning位于错误的元素上,或者主题将类更改为body,而不是属性更改为html。
当不需要八个主题时
大多数产品都有足够的光、暗和系统性。每个附加主题都是对所有组件状态对比的测试。当个性化是产品的一部分时,有八个主题是合理的:代码编辑器、开发人员工具、阅读器。