Tailwind CSS 工具类
Tailwind 的核心就是其庞大而全面的工具类(Utility Classes)库。这些类被精心设计,以“功能优先”的理念,让你能够直接在 HTML 中构建任何设计。本章将概述工具类的结构和一些常用类别。
工具类的结构
Tailwind 的工具类通常遵循一个可预测的格式:
{property}-{value} 或 {prefix}:{property}-{value}
{property}: 通常是 CSS 属性的缩写,例如bg代表background,p代表padding,text代表color和font-size等。{value}: 代表一个具体的值,通常来自你的tailwind.config.js中定义的设计系统。例如,red-500代表一个特定的红色,4代表1rem的间距。{prefix}: 可选的前缀,用于在特定条件下应用样式,例如hover:(悬停状态)或md:(中等屏幕尺寸)。
常用工具类类别
以下是你在日常开发中最常用到的一些工具类类别:
布局 (Layout)
- Display:
block,inline-block,inline,flex,grid,hidden等。 - Position:
static,relative,absolute,fixed,sticky。 - Top / Right / Bottom / Left:
top-0,left-4,bottom-auto等,支持任意值top-[10px]。 - Z-Index:
z-0,z-10,z-auto等。
Flexbox & Grid
- Flex Direction:
flex-row,flex-col。 - Flex Wrap:
flex-wrap,flex-nowrap。 - Align Items:
items-start,items-center,items-end。 - Justify Content:
justify-start,justify-center,justify-between。 - Grid Template Columns/Rows:
grid-cols-3,grid-rows-2。 - Gap:
gap-4,gap-x-8。
间距 (Spacing)
- Padding:
p-4(所有方向),px-6(水平方向),pt-2(上方)。 - Margin:
m-4(所有方向),mx-auto(水平居中),mt-8(上方)。
尺寸 (Sizing)
- Width:
w-16,w-1/2,w-full,w-screen,w-auto。 - Height:
h-16,h-full,h-screen。 - Min/Max Width/Height:
min-w-0,max-h-screen。
排版 (Typography)
- Font Family:
font-sans,font-serif,font-mono。 - Font Size:
text-xs,text-base,text-lg,text-4xl。 - Font Weight:
font-light,font-normal,font-bold。 - Text Color:
text-slate-500,text-sky-600。 - Text Align:
text-left,text-center,text-right。 - Text Decoration:
underline,line-through,no-underline。
背景 (Backgrounds)
- Background Color:
bg-white,bg-gray-800,bg-emerald-500。 - Background Image:
bg-cover,bg-center。
边框 (Borders)
- Border Radius:
rounded-none,rounded,rounded-lg,rounded-full。 - Border Width:
border,border-2,border-t-4(仅上边框)。 - Border Color:
border-gray-200,border-indigo-500。
效果 (Effects)
- Box Shadow:
shadow-sm,shadow,shadow-xl,shadow-inner。 - Opacity:
opacity-0,opacity-75,opacity-100。
这只是冰山一角。Tailwind 提供了数百个工具类。最好的学习方式不是去背诵它们,而是在需要时查阅 Tailwind CSS 官方文档。随着经验的积累,你会对常用的类越来越熟悉。