3.9 KiB
样式与自定义
关于主题、CSS 变量以及添加自定义颜色,请参阅 customization.md。
目录
- 语义化颜色
- 优先使用内置变体
- className 仅用于布局
- 避免 space-x-* / space-y-*
- 宽高相等时优先使用 size-*
- 优先使用 truncate 简写
- 不要手动覆写 dark: 颜色
- 使用 cn() 处理条件类名
- 浮层组件上不要手动设置 z-index
语义化颜色
错误写法:
<div className="bg-blue-500 text-white">
<p className="text-gray-600">辅助文本</p>
</div>
正确写法:
<div className="bg-primary text-primary-foreground">
<p className="text-muted-foreground">辅助文本</p>
</div>
状态/状态指示器不要使用原始颜色值
对于正向、负向或状态指示器,应使用 Badge 变体、text-destructive 等语义化标记,或定义自定义 CSS 变量——不要直接使用 Tailwind 原始颜色。
错误写法:
<span className="text-emerald-600">+20.1%</span>
<span className="text-green-500">活跃</span>
<span className="text-red-600">-3.2%</span>
正确写法:
<Badge variant="secondary">+20.1%</Badge>
<Badge>活跃</Badge>
<span className="text-destructive">-3.2%</span>
如果需要的成功/正向颜色不存在对应的语义化标记,请使用 Badge 变体,或请用户向主题中添加自定义 CSS 变量(参见 customization.md)。
优先使用内置变体
错误写法:
<Button className="border border-input bg-transparent hover:bg-accent">
点击我
</Button>
正确写法:
<Button variant="outline">点击我</Button>
className 仅用于布局
使用 className 处理布局(例如 max-w-md、mx-auto、mt-4),不要用它覆写组件的颜色或排版。如需修改颜色,请使用语义化标记、内置变体或 CSS 变量。
错误写法:
<Card className="bg-blue-100 text-blue-900 font-bold">
<CardContent>仪表盘</CardContent>
</Card>
正确写法:
<Card className="max-w-md mx-auto">
<CardContent>仪表盘</CardContent>
</Card>
若要自定义组件的外观,请按以下顺序优先选择:
- 内置变体——
variant="outline"、variant="destructive"等。 - 语义化颜色标记——
bg-primary、text-muted-foreground。 - CSS 变量——在全局 CSS 文件中定义自定义颜色(参见 customization.md)。
避免 space-x-* / space-y-*
请改用 gap-*。space-y-4 → flex flex-col gap-4。space-x-2 → flex gap-2。
<div className="flex flex-col gap-4">
<Input />
<Input />
<Button>提交</Button>
</div>
宽高相等时优先使用 size-*
使用 size-10 而非 w-10 h-10。适用于图标、头像、骨架屏等场景。
优先使用 truncate 简写
使用 truncate 而非 overflow-hidden text-ellipsis whitespace-nowrap。
不要手动覆写 dark: 颜色
使用语义化标记——它们通过 CSS 变量处理亮色/暗色主题。使用 bg-background text-foreground 而非 bg-white dark:bg-gray-950。
使用 cn() 处理条件类名
使用项目中的 cn() 工具函数处理条件性或合并的类名字符串。不要在 className 字符串中手动编写三元表达式。
错误写法:
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
正确写法:
import { cn } from "@/lib/utils"
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
浮层组件上不要手动设置 z-index
Dialog、Sheet、Drawer、AlertDialog、DropdownMenu、Popover、Tooltip、HoverCard 会自行处理层叠顺序。切勿添加 z-50 或 z-[999]。