Tailwind CSS 高手常用的 10 个技巧
Tailwind 不只是工具类,它有丰富的设计哲学。本文分享 10 个让开发体验更上一层楼的实战技巧。
Tailwind CSS 高手常用的 10 个技巧
Tailwind CSS 已经成为现代前端开发的事实标准。但很多人只用了它 20% 的能力。
下面分享 10 个实战中常用的高级技巧。
一、使用 @apply 抽取重复样式
/* globals.css */
@layer components {
.btn {
@apply inline-flex items-center px-4 py-2 rounded-lg font-medium transition-colors;
}
.btn-primary {
@apply btn bg-violet-600 text-white hover:bg-violet-700;
}
}
二、CSS 变量与 Tailwind 配合
// tailwind.config.ts
theme: {
extend: {
colors: {
brand: {
50: 'rgb(var(--brand-50) / <alpha-value>)',
500: 'rgb(var(--brand-500) / <alpha-value>)',
900: 'rgb(var(--brand-900) / <alpha-value>)',
},
},
},
}
/* globals.css */
:root {
--brand-50: 245 243 255;
--brand-500: 139 92 246;
--brand-900: 76 29 149;
}
这样可以运行时切换主题色!
三、group 与 peer 状态联动
<!-- group: 父元素状态触发子元素 -->
<a href="#" class="group">
<h3 class="group-hover:text-violet-600">标题</h3>
<p class="group-hover:underline">描述</p>
</a>
<!-- peer: 兄弟元素状态触发 -->
<input type="checkbox" class="peer hidden" id="toggle" />
<label for="toggle" class="peer-checked:bg-violet-600">
标签
</label>
四、任意值与自定义属性
<!-- 任意值 -->
<div class="top-[117px] grid-cols-[1fr_2fr]">
<!-- CSS 变量 -->
<div class="bg-[var(--my-color)]">
五、容器查询 (Container Queries)
// tailwind.config.ts
plugins: [require('@tailwindcss/container-queries')],
<div class="@container">
<div class="@lg:grid @lg:grid-cols-2">
<!-- 当父容器 >= lg 时变为两列 -->
</div>
</div>
六、自定义插件
// plugins/scrollbar.js
const plugin = require('tailwindcss/plugin');
module.exports = plugin(function ({ addUtilities }) {
addUtilities({
'.scrollbar-thin': {
'scrollbar-width': 'thin',
'&::-webkit-scrollbar': { width: '6px' },
'&::-webkit-scrollbar-thumb': {
'background-color': 'rgb(156 163 175)',
'border-radius': '3px',
},
},
});
});
七、暗色模式策略选择
// tailwind.config.ts
darkMode: 'class', // vs 'media'
class 模式 更灵活,可以手动控制;media 模式 跟随系统。
八、条件渲染的工具类
import { clsx } from 'clsx';
<div className={clsx(
'base-class',
isActive && 'bg-violet-600',
isDisabled && 'opacity-50 cursor-not-allowed'
)}>
或者使用内置的 cn 工具(类似 shadcn/ui):
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
九、动画与过渡
<!-- Tailwind 内置动画 -->
<div class="animate-pulse"> <!-- 脉冲 -->
<div class="animate-spin"> <!-- 旋转 -->
<div class="animate-bounce"> <!-- 弹跳 -->
<!-- 自定义动画 -->
// tailwind.config.ts
theme: {
extend: {
animation: {
'fade-in': 'fadeIn 0.5s ease-in-out',
},
keyframes: {
fadeIn: {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
},
},
}
十、生产环境优化
// next.config.js
module.exports = {
// 启用 JIT(默认已开启)
// 清除未使用的样式(PurgeCSS 默认集成)
};
确保 content 配置准确:
content: [
'./app/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
// 一定要包含所有包含类名的文件
],
写在最后
Tailwind 看似只是工具类的集合,但当你深入使用后,会发现它的设计哲学:
约束带来自由 — 限制选择反而提高效率。
希望这些技巧能帮你更高效地使用 Tailwind。如果有其他问题,欢迎交流! 🚀
回到首页感谢阅读 · 欢迎在下方留言