🎨 主题切换

跟随系统

🎨 CSS 多主题方案

CSS Variables 实现的完整主题切换系统

1. 当前主题配色

主背景
次背景
卡片
主文字
次文字
主色调
次色调
边框

3. 主题效果展示

功能卡片 1

这是一个示例卡片,展示主题切换后的效果。颜色会根据当前主题自动调整。

功能卡片 2

支持亮色、暗色和自定义主题,提供一致的用户体验。

功能卡片 3

使用 CSS Variables 实现,性能优秀,无需重新编译。

3
主题方案
12
配色变量
0ms
切换延迟
100%
浏览器支持

4. 实现代码

/* 1. 定义主题变量 */ :root { --bg-primary: #ffffff; --text-primary: #1a1a1a; --accent-primary: #667eea; } [data-theme="dark"] { --bg-primary: #0f172a; --text-primary: #f1f5f9; --accent-primary: #60a5fa; } /* 2. 使用变量 */ .card { background: var(--bg-primary); color: var(--text-primary); border-color: var(--accent-primary); transition: all 0.3s; /* 平滑过渡 */ } /* 3. JavaScript 切换主题 */ function setTheme(theme) { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('theme', theme); } /* 4. 跟随系统主题 */ const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)'); darkModeQuery.addEventListener('change', (e) => { setTheme(e.matches ? 'dark' : 'light'); }); /* 5. 恢复保存的主题 */ const savedTheme = localStorage.getItem('theme') || 'light'; setTheme(savedTheme);

5. 主题系统最佳实践

✅ 推荐做法:
• 使用语义化变量名(如 --text-primary 而不是 --color-1)
• 添加 transition 实现平滑过渡
• 保存用户主题偏好到 localStorage
• 支持系统主题自动切换
• 为所有交互元素提供主题适配

❌ 避免做法:
• 不要在 :root 中定义过多变量
• 避免在动画中频繁修改 CSS Variables
• 不要忘记处理图片、图标的主题适配
• 避免使用绝对颜色值(如 #fff),应使用变量