跳到主要内容
Ed. notes

07 样式与主题:tokens 与亮暗切换

长文 · 2026-11-12 · 合集第 8 / 10 篇

  • SCSS
  • CSS Modules
  • 主题
  • 设计系统
  • 构建日志
第 8 / 10 篇 · 查看全部章节 → 当前:07 样式与主题:tokens 与亮暗切换

结论

这个站的样式只有两个来源:design tokens 和组件自己的 CSS Modules。

app/assets/styles/_tokens.scss   编译期常量:字号、行高、间距、圆角、断点
app/assets/styles/_themes.scss   运行时颜色:--color-* 自定义属性
app/assets/styles/main.scss      全局重置、body、焦点兜底
组件 <style module lang="scss"> 只引用 token,不写死颜色和间距

颜色必须能在亮暗主题之间切换,所以用 CSS 自定义属性;字号、间距和断点在构建后不会变,所以用 SCSS 变量。这个分层决定了组件里写 tokens.$space-16 还是 var(--color-fg)。

问题与设计

为什么不用 Tailwind

不是 Tailwind 不好,而是这个站的视觉约束更适合语义 token:

  • 页面数量少,组件复用度高,样式跟着组件走更自然;
  • 需要亮暗主题,颜色必须集中在一处;
  • 设计 token 需要能被测试和文档引用,而不是散落在类名里;
  • 不希望 JSX/Vue 模板被一长串工具类占满。

SCSS 提供变量、mixin 和嵌套;CSS Modules 提供组件级作用域。两者组合后,组件的类名不会互相污染,全局样式只保留 reset、body 和焦点兜底。

两类 token

// 编译期常量
$space-16: 16px;
$radius-8: 8px;
$breakpoint-tablet: 768px;

// 运行时颜色
:root {
  --color-bg: #fafaf8;
  --color-fg: #191b1d;
}

[data-theme='dark'] {
  --color-bg: #111316;
  --color-fg: #f2f3f5;
}

组件里这样用:

.card {
  padding: tokens.$space-24;
  border: tokens.$border-1 solid var(--color-border);
  border-radius: tokens.$radius-8;
  background-color: var(--color-surface);
}

$space-24 编译后是固定的 24px;var(--color-surface) 在运行时随 data-theme 变化。两者不能互换:把颜色写成 SCSS 变量,主题切换就失效;把间距写成 CSS 变量,又失去了编译期约束。

断点与容器

断点只有四档:768、1024、1440,加上移动端默认值。media-up() 负责生成 min-width 查询:

@mixin media-up($breakpoint) {
  @media (min-width: $breakpoint) {
    @content;
  }
}

AppContainer 统一控制内容宽度:普通页面最宽 1200px,详情页和关于页收窄到 720px;左右边距随断点从 24px 增加到 120px。页面组件不需要自己算容器宽度。

主题切换:首屏前完成

如果等 Vue 挂载后再读 localStorage 并设置主题,用户会先看到一帧亮色,再闪成暗色。解决方式是在 nuxt.config.ts 里注入一段内联脚本,放在 <head>,在页面绘制前执行:

const key = 'fieldnotes-theme'
const stored = window.localStorage.getItem(key)
const preference =
  stored === 'light' || stored === 'dark' || stored === 'system' ? stored : 'system'
const dark =
  preference === 'dark' ||
  (preference === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
document.documentElement.dataset.theme = dark ? 'dark' : 'light'

这段脚本只做一件事:尽快把 data-theme 写到 <html> 上。真正的状态管理交给 useTheme()。

useTheme 的状态

useTheme() 维护两个值:

  • preference:用户选择,可能是 light、dark 或 system;
  • resolved:实际生效的 light 或 dark。

初始化时优先读 document.documentElement.dataset.theme,因为它已经由内联脚本算好;只有拿不到时才重新读存储和系统偏好。这样服务端渲染的 HTML 和客户端的首帧不会因为主题不同而错位。

切换时同时做三件事:更新状态、写 data-theme、把偏好写入 localStorage。如果偏好是 system,还监听 matchMedia('(prefers-color-scheme: dark)') 的变化。

关键代码

tokens 的语义阶梯

// 字号与行高成对使用
$text-body-md-size: 16px;
$text-body-md-line: 26px;
$text-h1-page-size: 48px;
$text-h1-page-line: 62px;

// 间距
$space-8: 8px;
$space-16: 16px;
$space-24: 24px;
$space-32: 32px;

// 焦点
$focus-ring-width: 2px;
$focus-ring-offset: 2px;

// 断点
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1024px;
$breakpoint-wide: 1440px;

组件不直接写 16px 或 24px,而是引用语义名。改间距阶梯时只改一处。

亮暗主题

:root {
  color-scheme: light;

  --color-bg: #fafaf8;
  --color-fg: #191b1d;
  --color-fg-muted: #5c6066;
  --color-surface: #fff;
  --color-border: #d8dadd;
  --color-focus-ring: rgb(0 0 0 / 72%);
}

[data-theme='dark'] {
  color-scheme: dark;

  --color-bg: #111316;
  --color-fg: #f2f3f5;
  --color-fg-muted: #abb1bb;
  --color-surface: #181c21;
  --color-border: #3b414a;
  --color-focus-ring: rgb(255 255 255 / 72%);
}

真实文件里的颜色更多,但结构只有这一组:亮色在 :root,暗色在 [data-theme='dark']。组件永远引用 var(--color-*),不出现十六进制值。

主题脚本

// frontend/nuxt.config.ts
const themeScript = `(() => {
  try {
    const key = 'fieldnotes-theme'
    const stored = window.localStorage.getItem(key)
    const preference =
      stored === 'light' || stored === 'dark' || stored === 'system' ? stored : 'system'
    const dark =
      preference === 'dark' ||
      (preference === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
    document.documentElement.dataset.theme = dark ? 'dark' : 'light'
  } catch {
    // 存储不可用时保持默认亮色。
  }
})()`

useTheme 的初始化与切换

const init = () => {
  if (!import.meta.client || initialized) return
  initialized = true

  const value = readStoredPreference()
  const current = document.documentElement.dataset.theme
  preference.value = value
  resolved.value =
    current === 'dark' || current === 'light' ? current : value === 'system' ? systemTheme() : value

  document.documentElement.dataset.theme = resolved.value

  mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', handleSystemChange)
}

const toggle = () => apply(resolved.value === 'dark' ? 'light' : 'dark')

apply() 会把偏好写入 localStorage 的 fieldnotes-theme。key 沿用旧名,是为了品牌改名后不重置已有用户的主题选择。

组件里的 CSS Modules

<style module lang="scss">
@use '../assets/styles/mixins' as mixins;
@use '../assets/styles/tokens' as tokens;

.card {
  padding: tokens.$space-24;
  border: tokens.$border-1 solid var(--color-border);
  border-radius: tokens.$radius-8;
  background-color: var(--color-surface);
}

.card:focus-visible {
  @include mixins.focus-ring;
}
</style>

模板里通过 $style.card 使用。类名会被编译成哈希,组件之间不会冲突。

验证

先跑样式和 token 相关检查:

cd frontend
npm run lint:styles
npm run test

npm run test 里包含 token 和对比度检查。再手动验证主题:

  1. 点击页头的主题按钮,页面应在亮暗之间切换;
  2. 刷新页面,主题保持不变;
  3. 打开 DevTools 的 Application,确认 localStorage 里有 fieldnotes-theme;
  4. 把系统主题改成暗色,在偏好为 system 时刷新,页面应跟随系统;
  5. 快速刷新页面,确认没有明显的亮暗闪烁。

最后检查四个宽度:390、768、1024、1440。每个宽度下不应出现横向滚动,卡片网格应从 1 列变成 2 列、3 列。

边界

  • 没有主题过渡动画;切换是瞬时的,避免在低性能设备上引入额外绘制。
  • 不支持用户自定义颜色,只有亮、暗、跟随系统三种选择。
  • 颜色只允许出现在 _themes.scss;组件里出现十六进制值应视为 bug。
  • 内联主题脚本在启用 CSP 时需要 nonce,当前配置还没有 CSP。
  • v-html 生成的正文节点拿不到 CSS Modules 类名,所以详情页用 article-prose 全局命名空间单独排版。
  • 完整的 token 说明、对比度标准和组件用法在 docs/design-system.md,更细的设计取舍在 构建实践。

下一篇进入交付:内容校验和样式都通过后,怎样构建镜像、用 Caddy 反向代理,并接上 CI 质量门。