# Tailwind v4 主题配置修复 ## 问题描述 项目使用 Tailwind CSS v4,但 `globals.css` 中的 `@theme` 配置使用了错误的语法: - 使用了 `var()` 引用(v4 不支持) - 定义了非标准的中间变量(如 `--bg-100`) - 使用了 `calc()` 计算(v4 中应直接使用值) ## 解决方案 ### 核心变更 1. **移除 CSS 变量引用** - ❌ `--color-background: var(--bg-100);` - ✅ `--color-background: #151931;` 2. **简化主题令牌** - 只保留 Tailwind 语义化颜色(`--color-*`) - 移除中间变量(`--bg-100/200/300`) 3. **使用 `@apply` 指令** - 在 `@layer base` 中使用 Tailwind 工具类 - 例:`@apply bg-background text-foreground` 4. **分离自定义变量** - 功能色(success/warning/error) - 轨道颜色(track-\*) - 布局尺寸(sidebar-width-\*) - 这些放在 `:root` 中,不在 `@theme` 内 ### 文件变更 **修改文件**:`client/src/styles/globals.css` **关键改动**: ```css /* ✅ 正确的 Tailwind v4 语法 */ @theme { --color-background: #151931; --color-primary: #86b9ff; --font-sans: "Inter", "PingFang SC", sans-serif; } /* ✅ 使用 @apply */ @layer base { body { @apply bg-background text-foreground; } } /* ✅ 自定义变量独立定义 */ :root { --color-success: #5eead4; --sidebar-width-collapsed: 60px; } ``` ## Tailwind v4 关键特性 1. **无需 `tailwind.config.js`** - 配置直接写在 CSS 中 - 使用 `@theme` 指令 2. **语义化令牌** - `--color-background` → `bg-background` - `--color-primary` → `bg-primary` - `--font-sans` → `font-sans` 3. **性能优化** - 按需编译 - 更快的构建速度 ## 验证方法 1. 重启开发服务器:`npm run dev` 2. 检查浏览器 DevTools: - 查看 `` 是否应用了 `background-color: #151931` - 检查按钮是否使用了 `--color-primary` 3. 测试组件: - 使用 `bg-primary` 类名 - 使用 `text-foreground` 类名 ## 参考资料 - [Tailwind CSS v4 文档](https://tailwindcss.com/docs/v4-beta) - [主题配置指南](https://tailwindcss.com/docs/theme) ## 补充修复:主题切换问题 ### 问题 切换亮色/暗色主题无反应,原因是使用了 `@media (prefers-color-scheme: light)` 而非类名选择器。 ### 解决方案 将 `@media (prefers-color-scheme: light)` 改为 `.light` 类选择器,配合 `settingsStore` 的 `applyTheme` 逻辑。 **修改前**: ```css @media (prefers-color-scheme: light) { :root { ... } } ``` **修改后**: ```css .light { --color-background: #ffffff; /* ... */ } ``` ### 工作原理 1. 用户点击主题切换按钮 2. `settingsStore.setTheme()` 被调用 3. `applyTheme()` 给 `` 添加 `.light` 或 `.dark` 类 4. CSS 根据类名应用对应的颜色变量 ### 验证 ```bash # 开发者工具检查 document.documentElement.classList # 应该包含 'light' 或 'dark' ```