Tailwind CSS v4 上手笔记

#CSS#前端

这个博客直接用上了 Tailwind v4。和 v3 最大的区别:配置从 JS 挪进了 CSS。

不再需要 tailwind.config.js

v3 的主题写在 tailwind.config.js 里,v4 直接写在 CSS 的 @theme 块中:

@import "tailwindcss";

@theme {
  --color-accent: #b45309;
  --font-serif: Georgia, serif;
}

--color-accent 会自动生成 text-accent、bg-accent、border-accent 这些工具类。少一个配置文件,少一层心智负担。

Vite 项目用插件接入

PostCSS 插件退位了,现在是专用的 Vite 插件:

// astro.config.mjs / vite.config.js
import tailwindcss from '@tailwindcss/vite';

export default {
  vite: { plugins: [tailwindcss()] },
};

然后在入口 CSS 写一行 @import "tailwindcss" 就完事,不需要 @tailwind base 那三行了。

两个小坑

  1. @tailwindcss/typography 插件要用 @plugin "@tailwindcss/typography" 在 CSS 里加载,不能写在 config 里。
  2. 自定义颜色如果写在 @theme 外面,不会生成工具类——我第一版就踩了这个,查了半天为什么 text-accent 不生效。

整体感受:v4 的方向是对的,配置即 CSS,少了一层抽象。