第 4 章:进阶特性
9/1/25About 7 min
第 4 章:进阶特性
学习目标
- 掌握 @apply 指令的使用和最佳实践
- 学会自定义工具类和组件抽取
- 理解 JIT 模式和按需生成机制
- 掌握 Tailwind CSS 4.1 的新特性和改进
@apply 指令
基本用法
@apply
指令允许你在自定义 CSS 中应用 Tailwind 的工具类:
/* styles.css */
.btn-primary {
@apply bg-blue-500 text-white font-semibold py-2 px-4 rounded-lg;
@apply hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500;
@apply transition-colors duration-200;
}
.card {
@apply bg-white rounded-lg shadow-md p-6;
}
.form-input {
@apply block w-full px-3 py-2 border border-gray-300 rounded-md;
@apply focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
}
<!-- 使用自定义组件类 -->
<button class="btn-primary">主要按钮</button>
<div class="card">卡片内容</div>
<input type="text" class="form-input" placeholder="请输入...">
最佳实践
/* 推荐:组件级别的抽取 */
.btn {
@apply font-semibold py-2 px-4 rounded-lg transition-colors duration-200;
@apply focus:outline-none focus:ring-2 focus:ring-offset-2;
}
.btn-primary {
@apply btn bg-blue-500 text-white;
@apply hover:bg-blue-600 focus:ring-blue-500;
}
.btn-secondary {
@apply btn bg-gray-200 text-gray-900;
@apply hover:bg-gray-300 focus:ring-gray-500;
}
/* 避免:过度抽取基础工具类 */
.text-large {
@apply text-lg; /* 不推荐,直接使用 text-lg 更好 */
}
条件应用
/* 使用 @apply 处理复杂状态 */
.nav-link {
@apply block px-3 py-2 text-gray-700 font-medium;
@apply hover:text-blue-600 hover:bg-blue-50;
@apply transition-all duration-200;
}
.nav-link.active {
@apply text-blue-600 bg-blue-50 border-r-2 border-blue-600;
}
/* 响应式 @apply */
.responsive-card {
@apply p-4 bg-white rounded-lg shadow;
}
@screen md {
.responsive-card {
@apply p-6 shadow-lg;
}
}
自定义工具类
添加自定义工具类
// tailwind.config.js
module.exports = {
theme: {
extend: {
spacing: {
'18': '4.5rem',
'88': '22rem',
},
fontSize: {
'xxs': '0.625rem',
},
colors: {
'brand': {
50: '#eff6ff',
500: '#3b82f6',
900: '#1e3a8a',
}
}
}
},
plugins: [
// 添加自定义工具类插件
function({ addUtilities }) {
const newUtilities = {
'.text-shadow': {
textShadow: '2px 2px 4px rgba(0,0,0,0.1)',
},
'.text-shadow-lg': {
textShadow: '4px 4px 8px rgba(0,0,0,0.2)',
},
'.backface-hidden': {
'backface-visibility': 'hidden',
},
'.perspective': {
perspective: '1000px',
}
}
addUtilities(newUtilities, ['responsive', 'hover'])
}
]
}
使用插件添加组件
// tailwind.config.js
module.exports = {
plugins: [
function({ addComponents, theme }) {
const components = {
'.btn': {
padding: `${theme('spacing.2')} ${theme('spacing.4')}`,
borderRadius: theme('borderRadius.md'),
fontWeight: theme('fontWeight.semibold'),
transition: 'all 0.2s',
'&:focus': {
outline: 'none',
boxShadow: `0 0 0 2px ${theme('colors.blue.500')}`,
}
},
'.btn-primary': {
backgroundColor: theme('colors.blue.500'),
color: theme('colors.white'),
'&:hover': {
backgroundColor: theme('colors.blue.600'),
}
},
'.btn-secondary': {
backgroundColor: theme('colors.gray.200'),
color: theme('colors.gray.900'),
'&:hover': {
backgroundColor: theme('colors.gray.300'),
}
}
}
addComponents(components)
}
]
}
自定义变体
// tailwind.config.js
module.exports = {
plugins: [
function({ addVariant }) {
// 添加自定义伪类变体
addVariant('not-first', '&:not(:first-child)')
addVariant('not-last', '&:not(:last-child)')
addVariant('hocus', ['&:hover', '&:focus'])
// 添加数据属性变体
addVariant('data-active', '&[data-active="true"]')
addVariant('data-loading', '&[data-loading="true"]')
}
]
}
<!-- 使用自定义变体 -->
<div class="not-first:mt-4 not-last:mb-4">
<button class="hocus:bg-blue-600 data-active:bg-green-500" data-active="true">
按钮
</button>
</div>
JIT 模式详解
什么是 JIT 模式
JIT (Just-In-Time) 模式是 Tailwind CSS 的按需编译模式,它会实时扫描你的代码并只生成实际使用的 CSS。
JIT 模式优势:
- 开发时文件更小
- 支持任意值
- 更快的构建速度
- 更好的热重载体验
启用 JIT 模式
// tailwind.config.js
module.exports = {
mode: 'jit', // Tailwind CSS 3.0+ 默认启用
purge: [
'./src/**/*.{html,js,ts,jsx,tsx,vue}',
'./public/index.html',
],
// 其他配置...
}
任意值支持
JIT 模式支持在方括号中使用任意值:
<!-- 任意颜色值 -->
<div class="bg-[#1da1f2]">Twitter 蓝色</div>
<div class="text-[rgb(255,0,0)]">红色文本</div>
<!-- 任意尺寸值 -->
<div class="w-[300px]">固定宽度 300px</div>
<div class="h-[50vh]">50% 视窗高度</div>
<div class="top-[117px]">精确定位</div>
<!-- 任意间距值 -->
<div class="p-[1.7rem]">自定义内边距</div>
<div class="m-[10px]">10像素外边距</div>
<!-- CSS 变量 -->
<div class="bg-[var(--main-color)]">使用 CSS 变量</div>
<!-- 复杂值 -->
<div class="bg-[url('/api/avatar')]">动态背景图片</div>
<div class="before:content-['★']">伪元素内容</div>
动态类名生成
<!-- 动态颜色 -->
<div class="bg-[{{ userColor }}]">用户自定义颜色</div>
<!-- 动态尺寸 -->
<div class="w-[{{ width }}px]">动态宽度</div>
<!-- 响应式任意值 -->
<div class="lg:w-[calc(100%-2rem)]">计算宽度</div>
JIT 模式注意事项
JIT 模式注意点
- 字符串拼接:避免动态生成类名字符串
- 白名单:确保
content
配置正确扫描所有文件 - 缓存:开发时可能需要重启以应用配置更改
- 任意值语法:必须使用正确的 CSS 语法
// 不推荐:动态字符串拼接
const color = 'blue'
className = `bg-${color}-500` // JIT 可能无法检测到
// 推荐:完整类名或安全列表
className = 'bg-blue-500'
// 或者在 tailwind.config.js 中添加到 safelist
Tailwind CSS 4.1 新特性
改进的 TypeScript 支持
// 类型安全的配置
import type { Config } from 'tailwindcss'
const config: Config = {
content: [
'./src/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {
colors: {
primary: {
50: '#eff6ff',
500: '#3b82f6',
950: '#172554',
}
}
},
},
plugins: [],
}
export default config
新增工具类
<!-- 新的容器查询支持 -->
<div class="@container">
<div class="@lg:text-xl">容器查询响应式</div>
</div>
<!-- 改进的网格工具 -->
<div class="grid grid-cols-subgrid">
<div class="col-span-2">子网格支持</div>
</div>
<!-- 新的逻辑属性 -->
<div class="ms-4 me-4">逻辑边距(支持 RTL)</div>
<div class="ps-4 pe-4">逻辑内边距</div>
性能改进
// 新的优化选项
module.exports = {
future: {
hoverOnlyWhenSupported: true, // 只在支持悬停的设备上启用悬停效果
},
experimental: {
optimizeUniversalDefaults: true, // 优化默认值
}
}
新的插件 API
// 使用新的插件 API
const plugin = require('tailwindcss/plugin')
module.exports = {
plugins: [
plugin(function({ addUtilities, matchUtilities, theme }) {
// 新的 matchUtilities 支持动态值
matchUtilities(
{
'grid-area': (value) => ({
'grid-area': value,
}),
},
{ values: theme('gridArea') }
)
}),
],
}
实战应用
构建设计系统
/* components.css */
@layer components {
/* 按钮组件系统 */
.btn {
@apply inline-flex items-center justify-center font-medium transition-all duration-200;
@apply focus:outline-none focus:ring-2 focus:ring-offset-2;
@apply disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-sm {
@apply text-sm px-3 py-1.5 rounded-md;
}
.btn-md {
@apply text-base px-4 py-2 rounded-lg;
}
.btn-lg {
@apply text-lg px-6 py-3 rounded-xl;
}
.btn-primary {
@apply btn bg-blue-600 text-white border-blue-600;
@apply hover:bg-blue-700 hover:border-blue-700;
@apply focus:ring-blue-500;
}
.btn-outline {
@apply btn bg-transparent border-2;
@apply text-blue-600 border-blue-600;
@apply hover:bg-blue-600 hover:text-white;
@apply focus:ring-blue-500;
}
/* 表单组件 */
.form-group {
@apply space-y-2;
}
.form-label {
@apply block text-sm font-medium text-gray-700;
}
.form-input {
@apply block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm;
@apply focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
@apply disabled:bg-gray-50 disabled:text-gray-500;
}
.form-error {
@apply text-sm text-red-600;
}
/* 卡片组件 */
.card {
@apply bg-white rounded-lg border border-gray-200 shadow-sm;
}
.card-header {
@apply px-6 py-4 border-b border-gray-200;
}
.card-body {
@apply p-6;
}
.card-footer {
@apply px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg;
}
}
使用设计系统
<!-- 表单示例 -->
<form class="max-w-md mx-auto space-y-6">
<div class="form-group">
<label for="email" class="form-label">邮箱地址</label>
<input
type="email"
id="email"
class="form-input"
placeholder="请输入邮箱"
>
<p class="form-error hidden">请输入有效的邮箱地址</p>
</div>
<div class="form-group">
<label for="password" class="form-label">密码</label>
<input
type="password"
id="password"
class="form-input"
placeholder="请输入密码"
>
</div>
<div class="flex space-x-4">
<button type="submit" class="btn btn-primary btn-md flex-1">
登录
</button>
<button type="button" class="btn btn-outline btn-md">
注册
</button>
</div>
</form>
<!-- 卡片示例 -->
<div class="card max-w-md mx-auto">
<div class="card-header">
<h3 class="text-lg font-semibold text-gray-900">用户信息</h3>
</div>
<div class="card-body">
<p class="text-gray-600">这里是卡片的主要内容区域...</p>
</div>
<div class="card-footer">
<div class="flex justify-end space-x-3">
<button class="btn btn-outline btn-sm">取消</button>
<button class="btn btn-primary btn-sm">确认</button>
</div>
</div>
</div>
小结
通过本章学习,你应该掌握了:
- @apply 指令:在自定义 CSS 中复用 Tailwind 工具类
- 自定义工具类:扩展 Tailwind 的功能以满足特定需求
- JIT 模式:按需编译和任意值支持
- 设计系统:使用 Tailwind 构建一致的组件库
- 新特性:Tailwind CSS 4.1 的改进和优化
这些进阶特性让你能够更好地组织代码、提高开发效率,并构建可维护的设计系统。