深色模式已成为现代网站标配。本文以 FreeBox 真实代码为例,不到 50 行 CSS 实现三档主题切换

核心原理

:root {
  --bg-primary: #0f0f1a;
  --text-primary: #e8e8f0;
}

[data-theme="light"] {
  --bg-primary: #f8f9fb;
  --text-primary: #1a1a2e;
}

body { background: var(--bg-primary); color: var(--text-primary); }

三档切换

使用 JavaScript 读写 document.documentElement 的 data-theme 属性:

// dark mode
document.documentElement.setAttribute("data-theme", "dark");
// light mode
document.documentElement.setAttribute("data-theme", "light");
// auto (follow system)
const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light");
关键技巧:使用 CSS Variables 的好处是只需切换一个属性就能影响所有组件。主题偏好存入 localStorage,下次访问自动恢复。