在 next.js 中利用 css 变量解决暗黑模式闪烁(fouc)的核心做法是:将主题切换逻辑移至服务端渲染阶段,通过 `next/head` 或全局样式注入 css 变量,确保 html 初始加载时即应用正确的颜色值。具体实现需在 `_app.tsx` 中检测系统偏好或本地存储,并立即设置根元素的 `--bg-color` 和 `--text-color` 等变量,避免客户端 javascript 执行前的白屏或亮色闪烁。

如何在 _app.tsx 中初始化 CSS 变量?
在 Next.js 的 `_app.tsx` 文件中,可以通过 `useEffect` 结合 `localStorage` 或 `matchMedia` 来同步 CSS 变量。首先定义一组 CSS 变量,然后在组件挂载时读取用户偏好,动态修改 `document.documentElement.style`。这样能确保在页面渲染初期就应用正确的主题,消除 FOUC。

import { useEffect } from 'react';
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
useEffect(() => {
const root = window.document.documentElement;
const isDark = localStorage.getItem('theme') === 'dark' ||
(!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches);
if (isDark) {
root.style.setProperty('--bg-color', '#000');
root.style.setProperty('--text-color', '#fff');
} else {
root.style.setProperty('--bg-color', '#fff');
root.style.setProperty('--text-color', '#000');
}
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
如何在全局样式中定义和使用 CSS 变量?
在全局样式文件(如 `globals.css`)中,使用 `:root` 选择器定义默认主题变量,并通过 `[data-theme="dark"]` 覆盖这些变量。这种写法允许通过切换 HTML 标签的属性来快速切换主题,同时保持代码的解耦。开发者只需在 JS 中修改属性,CSS 会自动响应。
htmlq 是一个命令行工具,使用 CSS 选择器从 HTML 中提取内容,相当于 jq 的 HTML 版本。该工具使用 Rust 编写,允许你通过 CSS 选择器将 HTML 管道化,直接从终端提取文本、属性和结构化内容。
立即学习“前端免费学习笔记(深入)”;

:root {
--bg-color: #ffffff;
--text-color: #000000;
}
[data-theme="dark"] {
--bg-color: #000000;
--text-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
当 localStorage 为空且系统偏好为亮色时,CSS 变量如何表现?
当 `localStorage` 中没有存储主题信息,且系统偏好设置为亮色时,CSS 变量将回退到 `:root` 中定义的默认值。此时,`--bg-color` 为白色,`--text-color` 为黑色,页面以亮色模式渲染。这一行为确保了在没有用户明确设置的情况下,页面仍能根据系统设置正确显示,避免视觉错乱。

















