第五章:主题与样式定制
使用CSS变量进行主题化
1. CSS变量基础
CSS变量(也称为自定义属性)是现代化主题定制的核心工具。在Shadcn中,我们通过CSS变量实现动态主题切换和统一风格管理。
:root {
--primary-color: #3b82f6;
--secondary-color: #64748b;
--border-radius: 0.375rem;
}
2. Shadcn的主题变量体系
Shadcn预设了一套完整的CSS变量体系,覆盖了颜色、间距、阴影等设计要素:
/* 颜色系统示例 */
--background: #ffffff;
--foreground: #020817;
--primary: #3b82f6;
--primary-foreground: #f8fafc;
3. 动态主题切换实现
通过修改根元素的CSS变量实现运行时主题切换:
// 切换暗色主题
document.documentElement.style.setProperty('--background', '#020817');
document.documentElement.style.setProperty('--foreground', '#f8fafc');
4. 主题扩展最佳实践
推荐的主题扩展模式:
- 保持变量命名一致性:遵循
--[类别]-[用途]的命名规范 - 分层定义变量:基础变量→语义变量→组件变量
- 提供默认回退值:
.card { background: var(--card-bg, var(--background)); }
5. 与Tailwind的集成
在tailwind.config.js中引用CSS变量:
module.exports = {
theme: {
extend: {
colors: {
primary: 'var(--primary)',
}
}
}
}
6. 主题持久化方案
结合localStorage实现用户主题偏好保存:
// 保存主题选择
localStorage.setItem('theme', 'dark');
// 初始化时加载
const savedTheme = localStorage.getItem('theme') || 'light';
applyTheme(savedTheme);
专业建议:建议将主题变量分类管理,可以创建
theme-light.css和theme-dark.css分开维护不同主题的变量值,通过类名切换实现完整主题包切换。
