Tailwind CSS 主题定制 @theme
为什么及怎么定义设计令牌
为什么要用 CSS-first 配置
在 Tailwind CSS v4 中,官方推荐用纯 CSS 来管理项目配置,而不是像 v3 那样维护一个 tailwind.config.js。
这种思路的核心是把「设计令牌」直接写在样式表里,和你的业务 CSS 放在一起,少一层配置文件的跳转。v4 通过 @import "tailwindcss" 引入框架,再用一组以 @ 开头的指令完成配置。
本篇重点讲其中最重要的一条:@theme。它用来定义你项目的设计令牌,也就是颜色、字体、间距等可复用的变量。
@theme 定义设计令牌
@theme 是一个 CSS 指令块,你在里面声明以 -- 开头的变量,Tailwind 会把它们自动转换成可用的工具类。
@import "tailwindcss";
@theme {
--color-brand: #4f46e5;
--font-display: "Inter", "PingFang SC", sans-serif;
--spacing-section: 6rem;
}
声明之后,--color-brand 会生成 bg-brand、text-brand、border-brand 等颜色类;--font-display 会生成 font-display;--spacing-section 会生成 p-section、m-section、gap-section 等间距类。
下面是一个完整可运行的例子。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<link rel="stylesheet" href="./style.css">
</head>
<body class="font-display bg-brand/10 text-brand">
<h1 class="text-3xl font-bold p-section">品牌标题</h1>
</body>
</html>
@import "tailwindcss";
@theme {
--color-brand: #4f46e5;
--font-display: "Inter", "PingFang SC", sans-serif;
--spacing-section: 3rem;
}
覆盖与扩展默认主题
覆盖默认主题
@theme 并不是只能新增变量,它也能覆盖 Tailwind 自带的默认值。默认主题里已经有一套 --color-*、--font-* 变量,你只要用同名变量重新赋值,就完成了覆盖。
@theme {
--color-blue-500: #2563eb;
--font-sans: "Inter", "PingFang SC", sans-serif;
}
覆盖后,bg-blue-500、font-sans 等类会用到新值。注意这种覆盖是基于变量名的,变量名要和默认主题保持一致才会命中。
扩展而非删除
如果你只想新增令牌、保留全部默认主题,直接在 @theme 里写新变量即可。默认主题不会被清空,新变量会和默认变量合并。
@theme {
--color-brand: #4f46e5;
--color-accent: #f59e0b;
}
这样 bg-brand、bg-accent 可用,同时 bg-blue-500 等默认类依然正常。
改主色的实战例子
很多项目希望把蓝色主色换成自己的品牌色。下面把主色改成紫色,并让按钮和链接都使用它。
@import "tailwindcss";
@theme {
--color-primary: #7c3aed;
--color-primary-hover: #6d28d9;
}
<a href="#" class="bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded">
主按钮
</a>
因为 --color-primary 生成了 bg-primary 与 hover:bg-primary-hover,你无需写任何额外 CSS 就能拿到一套主题色。
@theme inline 的用途
@theme 默认会把变量输出到 :root,供运行时使用。当你希望某些令牌「就地展开」到工具类定义里,而不是引用一个 CSS 变量时,可以用 @theme inline。
典型场景是引用其他设计系统(如你已有 --brand 定义)时,用 inline 让生成的工具类直接展开成最终值,避免多层变量嵌套。日常项目用普通 @theme 就够了,inline 属于进阶需求。
@theme inline {
--color-brand: var(--brand);
}
小结
@theme用于声明设计令牌,自动生成对应工具类- 同名变量可覆盖默认主题,新增变量则扩展默认主题
@theme inline用于把令牌就地展开,适合对接外部设计系统