首页 / Skills / 网页与界面设计 / 深浅色双主题 Light and Dark Theme
网页与界面设计

深浅色双主题 Light and Dark Theme

AIBarsMITSkill 语言: 英文
协议已核对不含脚本低风险
演示真实运行记录 · claude-sonnet-5-5 · 2026年10月
Using the light-dark-theme skill, plan how to add light and dark mode to a small server-rendered Nuxt 3 app that uses plain CSS. Today its colors are hard-coded hex values in components. Give the token approach, the root and head setup, the System/Light/Dark toggle, how to avoid the flash of the wrong theme and the hydration mismatch, and how you would verify it. You cannot run the app, so say what you could not check.
Skill: light-dark-theme
Read: references/token-starter.md

Plan: light and dark mode for the Nuxt 3 app (plain CSS, SSR)

I haven't looked at your code, so file names below are placeholders. I did not run anything.

1. Token approach

  1. Audit. Grep components for #[0-9a-fA-F]{3,8}, rgb(, hsl( and named colors, including inline style and SVG fill/stroke attributes. Group the values by role. A handful of distinct grays usually collapses into 3–4 surface and text roles.
  2. Define role tokens, never value-named ones, in assets/css/theme.css. Register it in nuxt.config.ts under css: ['~/assets/css/theme.css']. Role tokens:
    • Surfaces: --bg, --surface, --surface-raised, --surface-input.
    • Text: --text, --text-secondary, --text-disabled, --text-inverse, --link.
    • Borders and focus: --border, --border-strong, --focus-ring.
    • Brand: --primary, --primary-hover, --on-primary.
    • Status: --success, --warning, --danger, --info, each with an --on-* token.
    • --shadow.
  3. Pick values. Seed from the skill's starter palette, then substitute your brand colors. Set each dark value deliberately, with no filter: invert and no mechanical lightness flip. Re-tune the status colors per theme.
  4. Migrate components. Replace every hex with var(--token). No .dark .card {} overrides. Switch SVG icons to currentColor.

2. Root and head setup

CSS, using data-theme on <html> as the single switch:

:root { color-scheme: light; /* light tokens */ }

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) { color-scheme: dark; /* dark tokens */ }
}
:root[data-theme="dark"] { color-scheme: dark; /* dark tokens */ }

The dark tokens appear twice. To keep the copies from drifting, I'd generate one from the other with a small build step (PostCSS or a script). If that is too heavy, I'd put a comment on both blocks and add a check that diffs them.

Head setup in nuxt.config.ts:

app: {
  head: {
    meta: [
      { name: 'color-scheme', content: 'light dark' },
      { name: 'theme-color', content: '#ffffff', media: '(prefers-color-scheme: light)' },
      { name: 'theme-color', content: '#0f1115', media: '(prefers-color-scheme: dark)' },
    ],
    script: [{
      innerHTML: `(function(){try{var s=localStorage.getItem('theme');if(s==='light'||s==='dark')document.documentElement.setAttribute('data-theme',s)}catch(e){}})()`,
      tagPosition: 'head',
    }],
  },
},

Nuxt/unhead renders a script with innerHTML as an inline, synchronous <script> in the server HTML. I'd check the rendered HTML to confirm it has no defer, async or type="module". Also check that the project's CSP, if it has one, allows inline scripts, with a nonce or hash if needed. Without a stored choice the script does nothing, so the media query handles System.

3. System / Light / Dark toggle

A useTheme() composable plus a ThemeToggle.vue component:

  • State: choice is 'system' | 'light' | 'dark'.
  • Select Light or Dark: set data-theme and write localStorage.theme.
  • Select System: remove the attribute and remove the key. Never store the word "system".
  • Storage access: wrap every read and write in try/catch.
  • System changes: while the choice is System, listen to matchMedia('(prefers-color-scheme: dark)') changes. This matters mainly for theme-color and for any JS that reads the theme. CSS follows the media query on its own.
  • Markup: a three-option radio group (<fieldset> with role="radiogroup") or three buttons with aria-pressed. It shows the current choice and has an accessible name.

4. Avoiding the flash and the hydration mismatch

Flash.

  • The inline head script sets data-theme before first paint.
  • <meta name="color-scheme"> plus color-scheme in CSS prevents a white canvas.
  • No theme transitions on first paint. Add a theme-ready class after mount if you want them.

Hydration mismatch. The server can't know the saved choice, so the server HTML must not depend on it.

  • Initialize choice to 'system' identically on server and client, and read storage only in onMounted.
  • Don't use useState or useCookie to render a different icon or label per theme.
  • Make the toggle's visual state not depend on JS state at first render. Two options: render the control's checked state only after mount, or drive it from CSS with :root[data-theme="dark"] .opt-dark { … }.
  • Don't bind data-theme through Vue on <html>. The head script owns it, and a Vue-managed attribute can conflict with it on hydration.
  • Never branch on import.meta.client or window during render.

5. Other items to handle

  • Logos and images with baked-in backgrounds: use <picture> with a media query, or a variant switched by data-theme. Note that <picture> follows the system setting, not the manual choice, so for a manual override use two <img> elements toggled by CSS.
  • Shadows, selection color, scrollbars, code blocks, charts, and third-party embeds. Embeds may remain known gaps.
  • Print styles and email templates should stay light, set explicitly.

6. Verification

Contrast, checked per theme and per state (hover, focus, disabled, error, placeholder, link):

  • --text on --bg, --surface and --surface-raised.
  • --text-secondary on --bg and --surface.
  • --link on --bg and --surface.
  • --on-primary on --primary and --primary-hover.
  • Each --on-<status> on its status color.
  • --border-strong and --focus-ring against their surfaces (3:1).
  • Placeholder on --surface-input.

I'd compute these ratios with a script from the token values, which needs no browser. Thresholds are 4.5:1 for text and 3:1 for large text and UI parts.

Browser matrix, at phone and desktop widths:

  • First load with no stored choice (system light and system dark), stored light, and stored dark. Throttle CPU and cache to catch any flash.
  • Hard reload and client-side navigation.
  • Toggle persists across reloads. System follows the OS.
  • Storage blocked (private window or blocked site data): the page still renders correctly.
  • Console shows no hydration warning.
  • Keyboard focus rings visible in both themes. No text, icon or border disappears.
  • curl the SSR HTML to confirm the inline script is in <head> and the toggle markup has no theme-dependent content.
  • Grep for leftover hard-coded colors.

What I could not check

I can't run the app, so none of the following is verified:

  • Any visual result in either theme.
  • The actual flash behavior.
  • Hydration warnings.
  • Real contrast of your brand colors. Starter values are placeholders, and the ratios have to be re-checked once your colors are in.
  • Behavior at phone and desktop widths.
  • Toggle persistence and OS-follow behavior.
  • Blocked-storage behavior.
  • Which unhead version and CSP settings your app has, which affects the inline script.
  • Whether your images, charts or embeds have theme problems, because I haven't seen them.

Real run in an isolated folder with only this skill installed. Only the Skill and Read tools were enabled, so no command was run and no file was written. The scenario is fictional and the model had no access to the code. The model opened the skill's token starter file.

它做什么

一套为网页界面添加或修复深浅色模式的分步方法。它先看项目的框架和已有的主题体系,然后按角色定义语义令牌(背景、文字、边框、品牌色和状态色及其“其上文字色”),而不是直接写十六进制颜色。它用根元素上的一个 data-theme 属性来切换主题,默认跟随系统设置,并始终设置 color-scheme,让原生控件和滚动条跟着变。它用放在 head 里的一小段同步脚本防止闪出错误主题,读取已保存的选择时包在 try/catch 里,并说明服务端渲染页面怎么避免水合不一致。切换器有三个状态:跟随系统、浅色、深色。

检查与修复

它列出了如何在每种主题、每个状态下检查对比度(普通文字 4.5:1,大号文字和有意义的界面部件 3:1),以及常见问题来源:写死的颜色、白底图片、没用 currentColor 的图标、阴影、图表、第三方嵌入、代码块和打印样式。一份参考文件提供了起步用的令牌,其中的占位颜色已经按它自己列出的对比度组合核算过。

适合什么场景

给已有网站加深色模式,或修复看起来不对的深色主题。

说明与风险

低风险:纯指令文件,没有脚本,不联网、不写文件。它会给出 CSS 和一小段内联脚本,要加进你自己的项目,上线前请先审阅。起步用的颜色只是占位:已按 Skill 列出的对比度组合核算过,但你换上品牌色之后必须重新核对。它看不到你正在运行的页面,会说明哪些检查没有做。较新的 CSS 和 meta 特性在不同浏览器的支持不同,请对照你的目标浏览器。AIBars 原创(MIT)。已用一个虚构的 Nuxt 应用试用过一次。