Tailwind CSS 指令与函数
Tailwind CSS 指令与函数学习笔记一、总览Tailwind CSS 的指令与函数分为两大类类别作用域用途指令DirectivesCSS 文件中控制 Tailwind 的编译行为函数FunctionsCSS 文件 / 配置文件中动态引用主题值二、指令Directives2.1tailwind— 注入 Tailwind 各层样式/* 必须的三行通常放在主 CSS 文件顶部 */tailwindbase;/* 注入 Preflight 重置 base 层样式 */tailwindcomponents;/* 注入 components 层样式 */tailwindutilities;/* 注入 utilities 层样式 */各层内容说明指令注入内容CSS 优先级tailwind basePreflightCSS Resetlayer base中的样式最低tailwind componentslayer components中的样式 插件注册的组件中tailwind utilities所有工具类 layer utilities中的样式最高Tailwind v4 变化v4 使用import tailwindcss一行替代三行tailwind。/* Tailwind v4 */importtailwindcss;2.2layer— 声明样式所属层级/* 将自定义样式归入 Tailwind 的层级体系 */layerbase{html{-webkit-font-smoothing:antialiased;}:root{--color-primary:#2563eb;}}layercomponents{.btn{applyinline-flex items-center justify-center rounded-md px-4 py-2;}}layerutilities{.text-balance{text-wrap:balance;}}层级优先级规则layer base layer components layer utilities 无 layer 的样式 最低 中 高 最高关键要点同一层级内后定义的规则覆盖先定义的不在layer中的样式优先级最高可覆盖所有层级一个layer可以出现多次同名的层会自动合并/* 分散定义自动合并到同一层 */layercomponents{.btn{/* ... */}}layercomponents{.card{/* ... */}}/* 等价于在一个 layer components 中定义 .btn 和 .card */2.3apply— 在 CSS 中使用工具类将 Tailwind 工具类内联到自定义 CSS 规则中layercomponents{.btn-primary{applybg-blue-600 text-white rounded-md px-4 py-2 font-medium transition-colorshover:bg-blue-700focus-visible:ring-2focus-visible:ring-blue-500focus-visible:ring-offset-2disabled:opacity-50;}}apply支持的特性/* 支持变体修饰符 */.card{applyrounded-lg bg-white shadow-sm;applyhover:shadow-md;/* 伪类变体 */applyfocus-visible:ring-2;/* 焦点变体 */applydark:bg-gray-800;/* 暗色模式 */applysm:text-baselg:text-lg;/* 响应式 */applygroup-hover:scale-105;/* 群组变体 */}/* 支持重要修饰符 */.important-style{apply!text-red-500 !font-bold;}apply不支持的场景/* ❌ 不能使用需要 DOM 上下文的变体 */.btn{applypeer-disabled:opacity-50;/* peer 需要兄弟元素 */}/* ❌ 不能使用任意值中的模板语法 */.btn{applytext-[var(--my-color)];/* 某些复杂任意值可能不工作 */}/* ❌ 不能 apply 自身循环引用 */.circular{applycircular;/* 无限循环 */}2.4variants/responsive/screen已废弃Tailwind v3 中这些指令已被变体修饰符取代仅作了解。/* ❌ 旧写法v2 及之前 */responsive{.card{padding:1rem;}}variantshover,focus{.btn{opacity:0.8;}}screenmd{.container{max-width:768px;}}/* ✅ 新写法v3— 直接用变体前缀 */layercomponents{.card{applyp-4md:p-6;}.btn{applyhover:opacity-80focus:opacity-80;}}2.5source— 控制内容扫描范围v4/* Tailwind v4 新增指定额外的扫描路径 */source../node_modules/my-ui-lib/**/*.js;/* 排除路径 */source not../node_modules/some-lib/**/*.js;2.6theme— 内联定义主题v4/* Tailwind v4 新增直接在 CSS 中定义主题 */theme{--color-brand:#3b82f6;--font-display:Cal Sans,sans-serif;--breakpoint-xs:475px;}三、函数Functions3.1theme()— 引用主题配置值在 CSS 中动态获取tailwind.config.js中定义的主题值/* 基本用法获取单层值 */.card{border-radius:theme(borderRadius.lg);/* 0.5rem */padding:theme(spacing.6);/* 1.5rem */color:theme(colors.gray.900);/* #111827 */font-size:theme(fontSize.xl);/* 1.25rem */box-shadow:theme(boxShadow.md);/* 0 4px 6px -1px ... */}/* 获取带行高的字体大小返回完整对象值 */h1{font-size:theme(fontSize.2xl);/* 1.5rem */line-height:theme(lineHeight.2xl);/* 2rem *//* 注意fontSize 的 theme() 只返回字号值不含行高 */}在apply中不能使用theme()/* ❌ 错误 */.btn{applytheme(colors.blue.500);/* apply 只接受类名 */}/* ✅ 正确 — 用原生 CSS 属性 */.btn{background-color:theme(colors.blue.500);}theme()支持点号路径/* 对应配置结构 */div{/* theme.extend.colors.brand.500 */color:theme(colors.brand.500);/* theme.extend.spacing.128 */width:theme(spacing.128);/* 嵌套路径用 . 连接 */border-color:theme(colors.gray.200);}theme()带默认值/* 如果路径不存在不会报错返回空 *//* Tailwind 本身不直接支持 theme() 默认值语法 *//* 但可以用 CSS 自定义属性做 fallback */.card{/* 利用 CSS var 的 fallback */--my-radius:theme(borderRadius.xl);border-radius:var(--my-radius,0.5rem);}3.2theme()在配置文件中的使用在tailwind.config.js中通过函数参数访问主题值module.exports{theme:{extend:{// 在 extend 中无法直接引用自身需要用函数形式boxShadow:{brand:(theme)0 0 20px${theme(colors.brand.500)}40,},},},// 插件中通过参数获取 theme 函数plugins:[plugin(function({addUtilities,theme}){addUtilities({.text-gradient-brand:{backgroundImage:linear-gradient(to right,${theme(colors.brand.500)},${theme(colors.purple.500)}),WebkitBackgroundClip:text,WebkitTextFillColor:transparent,},});}),],};3.3screen()— 响应式断点函数v4/* Tailwind v4 新增在 CSS 中使用断点 */mediascreen(md){.container{max-width:768px;}}/* 等价于 */media(min-width:768px){.container{max-width:768px;}}四、指令与函数的完整速查指令速查指令版本用途示例tailwindv2注入各层样式tailwind utilitieslayerv2声明样式层级layer components { }applyv2CSS 中引用工具类apply bg-white p-4variantsv2v3 废弃包裹变体样式variants hover { }responsivev2v3 废弃包裹响应式样式responsive { }screenv2v3 废弃媒体查询快捷方式screen md { }sourcev4控制扫描范围source ../lib/**/*.jsthemev4CSS 内定义主题theme { --color-*: ... }import tailwindcssv4替代三行 tailwind一行引入全部函数速查函数用途使用位置示例theme()引用主题值CSS 规则中color: theme(colors.blue.500)theme参数引用主题值配置文件插件中theme(spacing.4)screen()响应式断点CSS media 中v4media screen(md) { }五、实战组合示例5.1 完整 CSS 入口文件/* 1. 引入 Tailwind */tailwindbase;tailwindcomponents;tailwindutilities;/* 2. Base 层全局基础 */layerbase{html{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;scroll-behavior:smooth;}:root{--color-bg:theme(colors.white);--color-text:theme(colors.gray.900);--color-brand:theme(colors.blue.600);--header-h:theme(spacing.16);}.dark{--color-bg:theme(colors.gray.900);--color-text:theme(colors.gray.100);--color-brand:theme(colors.blue.400);}body{background-color:var(--color-bg);color:var(--color-text);}}/* 3. Components 层组件样式 */layercomponents{.btn{applyinline-flex items-center justify-center rounded-md px-4 py-2 text-sm font-medium transition-colors duration-150focus-visible:outline-nonefocus-visible:ring-2disabled:pointer-events-nonedisabled:opacity-50;}.btn-primary{applybtn bg-blue-600 text-whitehover:bg-blue-700focus-visible:ring-blue-500;}.btn-ghost{applybtn bg-transparent text-gray-700hover:bg-gray-100focus-visible:ring-gray-500dark:text-gray-300dark:hover:bg-gray-800;}.card{border-radius:theme(borderRadius.xl);background-color:theme(colors.white);box-shadow:theme(boxShadow.sm);border:1px solidtheme(colors.gray.200);padding:theme(spacing.6);}.dark .card{background-color:theme(colors.gray.800);border-color:theme(colors.gray.700);}}/* 4. Utilities 层自定义工具类 */layerutilities{.text-balance{text-wrap:balance;}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none;::-webkit-scrollbar{display:none;}}.mask-fade-bottom{mask-image:linear-gradient(to bottom,black 60%,transparent 100%);}}5.2 配合配置文件// tailwind.config.jsconstpluginrequire(tailwindcss/plugin);module.exports{content:[./src/**/*.{html,js,jsx,ts,tsx,vue}],theme:{extend:{colors:{brand:{50:#eff6ff,500:#3b82f6,600:#2563eb,700:#1d4ed8,},},keyframes:{shimmer:{100%:{transform:translateX(100%)},},},animation:{shimmer:shimmer 2s infinite,},},},plugins:[plugin(function({addUtilities,theme}){// 使用 theme() 函数引用配置值addUtilities({.glow-brand:{boxShadow:0 0 20px${theme(colors.brand.500)}50,},.gradient-brand:{backgroundImage:linear-gradient(135deg,${theme(colors.brand.500)},${theme(colors.purple.500)}),},});}),],};六、常见问题与陷阱问题原因解决方案apply的类不生效类名不在content扫描范围内确保 HTML/组件文件在content配置中theme()返回空值路径写错或值未定义检查路径colors.brand.500而非brand.500layer中样式被覆盖层级优先级base components utilities将覆盖样式放到更高层级apply中使用!important语法特殊用!前缀apply !text-red-500apply循环引用类引用自身拆分为更小的类或改用原生 CSSv3 中screen不工作v3 已废弃screen改用media (min-width: theme(screens.md))theme()在apply中不可用apply只接受类名改用原生 CSS 属性 theme()七、v3 → v4 迁移对照v3 写法v4 写法tailwind base;tailwind components;tailwind utilities;import tailwindcss;tailwind.config.js中定义主题theme { }在 CSS 中定义content: [...]在配置文件中source在 CSS 中指定media (min-width: 768px)media screen(md)theme(colors.blue.500)var(--color-blue-500)v4 自动生成 CSS 变量v4 的核心变化配置从 JS 迁移到 CSS主题值自动暴露为 CSS 变量减少了对theme()函数的依赖。