SuperAPI AI 工具集

tailwind

前端与建站

查看项目

更新于 10-16 04:17

技能介绍

用途

本技能面向 Tailwind CSS v4+ 的现代工具类优先(utility-first)CSS 开发,提供 v4 版本的最佳实践参考,帮助在项目中正确使用 v4 的新配置方式与特性。

v4 的主要变化

资料以对比表形式列出 v3 与 v4 的差异:

  • 配置方式:v3 使用 tailwind.config.js,v4 改为 CSS-first 配置(@theme)。
  • 颜色定义:v3 使用 JS 对象,v4 使用 CSS 变量。
  • 性能:v3 使用 JIT,v4 使用 Oxide 引擎(更快)。
  • 导入语法:v3 使用 @tailwind base,v4 使用 @import "tailwindcss"。

安装与接入

v4 安装命令为:

npm install tailwindcss@next @tailwindcss/vite

Vite 配置示例(vite.config.ts):

import tailwindcss from '@tailwindcss/vite'

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

CSS-first 配置

在 app.css 中通过 @import "tailwindcss" 引入,并使用 @theme 定义设计令牌,包括颜色(如 --color-primary、--color-secondary、--color-accent,以及自定义色阶 --color-brand-50/500/900)、字体(--font-sans、--font-mono)、间距(--spacing-18、--spacing-128)、圆角(--radius-4xl)、阴影(--shadow-soft)和动画(--animate-fade-in)。动画可配合 @keyframes 定义关键帧。

暗色模式

采用 CSS-first 暗色模式:在 @theme 中定义默认的 --color-background 与 --color-foreground,再通过 @theme dark 覆盖为暗色值。组件中使用 bg-background、text-foreground 等类名,切换时在 html 上添加 dark 类。

响应式设计

遵循移动优先原则,通过断点前缀逐级覆盖,例如内边距 p-4 / md:p-6 / lg:p-8 / xl:p-12,标题字号 text-xl / md:text-2xl / lg:text-4xl。

容器查询

v4 支持容器查询:父元素使用 @container,子元素使用 @md:flex、@lg:grid、@lg:grid-cols-3 等,响应的是容器尺寸而非视口。

组件模式

资料给出按钮变体(primary、secondary、outline、ghost)、卡片模式(圆角、明暗背景、阴影、内边距、边框)和输入框模式(宽度、圆角、边框、明暗背景、内边距、文字颜色、placeholder 颜色、focus ring、disabled 状态)的类名写法示例。

动画工具类

包括悬停效果(transition-all、hover:scale-105、hover:shadow-lg、active:scale-95)、入场动画(animate-fade-in)和骨架屏加载(animate-pulse)。

网格布局

提供自动适配网格 grid-cols-[repeat(auto-fit,minmax(250px,1fr))] 与 12 列仪表盘布局(侧边栏 col-span-12 md:col-span-3,主内容 col-span-12 md:col-span-9)示例。

自定义工具类

v4 使用 @utility 定义自定义工具类,例如 glass(半透明背景、backdrop-filter 模糊、边框)和 text-gradient(线性渐变文字)。

性能建议

推荐使用 cn() 处理条件类名,避免大量条件拼接的模板字符串。cn() 由 clsx 与 tailwind-merge 组合实现:

import { clsx, type ClassValue } from 'clsx'; import { twMerge } from 'tailwind-merge';

export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }

适用场景

适用于使用 Tailwind CSS v4 的前端项目,尤其是需要 CSS-first 主题定制、暗色模式、响应式与容器查询、组件样式复用和性能优化的场景。

限制

资料未提供具体版本号、浏览器兼容范围、构建工具之外的框架集成方式、收费或授权信息,这些内容暂未提供。