指令
指令以@开头,符合CSS语法规则,目的是为了为Tailwind CSS项目提供特殊功能
@tailwind
使用@tailwind指令为项目提供Tailwind的基础样式、组件样式、实用程序样式和功能类前缀
/*
@tailwind <bucket> --- 每一个都是一个样式桶
样式桶中的样式可以是tailwind默认提供的,也可以是通过插件注入的
*/
/* 基础样式 --- 样式重置和默认样式 */
@tailwind base;
/* 组件样式 --- 按钮, 输入框, 表单, 表格的功能类 */
@tailwind components;
/* 单一属性类 --- 宽度、高度、颜色、边距、填充等 */
@tailwind utilities;
/*
功能类前缀
+ 省略 --- 按需引入功能类前缀,并将其插入到css最后
+ 显示指定 --- 全量引入功能类前缀,并将其插入到css最后
*/
@tailwind variants;
@layer
@layer指令可以将自定义样式添加到对应的样式桶中, 有效值为base、components或utilities
使用@layer添加的自定义功能类可以使用任何的功能类修饰符前缀,并且可以实现按需引用
使用 @layer 添加的样式会被添加到对应的样式桶的末尾,以确保自定义样式能够覆盖之前的样式
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h1 {
@apply text-2xl;
}
h2 {
@apply text-xl;
}
}
@layer components {
.btn-blue {
@apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
}
}
@layer utilities {
.filter-none {
filter: none;
}
.filter-grayscale {
filter: grayscale(100%);
}
}
@apply
@apply 是一个 CSS 的语法规则,可以让你把已经存在的一些 CSS 样式直接应用到你自己写的 CSS 样式中
使用@apply可以很好的覆盖一些不是基于Tailwind编写的第三方库的样式
默认情况下,使用@apply添加的功能类不具有!important
如果需要具备!important,只需要在添加的样式的末尾添加!important即可
/* Input */
.btn {
@apply font-bold py-2 px-4 rounded !important;
}
/* Output */
.btn {
font-weight: 700 !important;
padding-top: .5rem !important;
padding-bottom: .5rem !important;
padding-right: 1rem !important;
padding-left: 1rem !important;
border-radius: .25rem !important;
}
像 Vue 和 Svelte 这样的框架在底层会独立处理每个 <style> 块,并针对每个块单独运行 PostCSS 插件链
所以会导致通过全局样式桶注入的自定义功能类,无法在组件的<style>块中被解析
为此Tailwind提供了插件系统,以解决这个问题
// tailwind.config.ts
const plugin = require('tailwindcss/plugin')
module.exports = {
// 这种方法可以让任何由 Tailwind 处理的文件都可以使用这个配置文件中定义的样式
// 但最好不要滥用 @apply 功能来做这样的事情,以获取更好的开发体验
plugins: [
plugin(function ({ addComponents, theme }) {
addComponents({
'.card': {
backgroundColor: theme('colors.white'),
borderRadius: theme('borderRadius.lg'),
padding: theme('spacing.6'),
boxShadow: theme('boxShadow.xl'),
}
})
})
]
}
@config
使用 @config 指令来指定 Tailwind 在编译该 CSS 文件时应该使用哪个配置文件
/*
@import有语法限制,必须位于css文件的最前边(注释不算)
所以对应的顺序为
@import xxx;
@config xxx;
@tailwind xxx;
*/
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
/* @config对应的路径是相对于当前css文件路径而言的 */
@config "./tailwind.prod.config.js";
@tailwind base;
@tailwind components;
@tailwind utilities;
函数
Tailwind 添加了一些会在构建阶段执行的自定义函数,这些函数会在构建的时候被执行,以确保在运行时对应的函数会被静态值替换
theme()
使用 theme() 函数使用点符号访问 Tailwind 配置值
.content-area {
/*
spacing-12 ---> spacing.12
spacing-2.5 ---> spacing[2.5]
colors-blue-500 ---> colors.blue.500
bg-sky-500/75 ---> bg.sky.500 / 75% ==> 75%表示透明度为0.75
*/
height: calc(100vh - theme(spacing.12));
}
screen()
使用 Tailwind 的 screen 函数,可以使用 Tailwind 预设的响应式断点来编写媒体查询,而不必手动输入具体的断点值,从而使 CSS 代码更加简洁易读,同时也方便维护和更新
/* input */
@media screen(sm) {
/* ... */
}
/* output */
@media (min-width: 640px) {
/* ... */
}