1. 核心概念
  2. 函数和指令

指令

¥Directives

指令是自定义的特定于 Tailwind 的 at-rules,你可以在 CSS 中使用它,为 Tailwind CSS 项目提供特殊功能。

¥Directives are custom Tailwind-specific at-rules you can use in your CSS that offer special functionality for Tailwind CSS projects.

@tailwind

使用 @tailwind 指令将 Tailwind 的 basecomponentsutilitiesvariants 样式插入到你的 CSS 中。

¥Use the @tailwind directive to insert Tailwind’s base, components, utilities and variants styles into your CSS.

/**

 * This injects Tailwind's base styles and any base styles registered by

 * plugins.
 */
@tailwind base;

/**

 * This injects Tailwind's component classes and any component classes

 * registered by plugins.
 */
@tailwind components;

/**

 * This injects Tailwind's utility classes and any utility classes registered

 * by plugins.
 */
@tailwind utilities;

/**

 * Use this directive to control where Tailwind injects the hover, focus,

 * responsive, dark mode, and other variants of each class.

 *  * If omitted, Tailwind will append these classes to the very end of

 * your stylesheet by default.
 */
@tailwind variants;

@layer

使用 @layer 指令告诉 Tailwind 一组自定义样式属于哪个 “bucket”。有效图层为 basecomponentsutilities

¥Use the @layer directive to tell Tailwind which “bucket” a set of custom styles belong to. Valid layers are base, components, and utilities.

@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%);
  }
}

Tailwind 会自动将任何 @layer 指令中的 CSS 移动到与对应的 @tailwind 规则相同的位置,因此你不必担心按特定顺序编写 CSS 以避免特异性问题。

¥Tailwind will automatically move the CSS within any @layer directive to the same place as the corresponding @tailwind rule, so you don’t have to worry about authoring your CSS in a specific order to avoid specificity issues.

添加到图层的任何自定义 CSS 仅当该 CSS 实际用于你的 HTML 时才会包含在最终构建中,就像默认内置到 Tailwind 中的所有类一样。

¥Any custom CSS added to a layer will only be included in the final build if that CSS is actually used in your HTML, just like all of the classes built in to Tailwind by default.

使用 @layer 封装任何自定义 CSS 还可以使用具有这些规则的修饰符,如 hover:focus: 或响应式修饰符,如 md:lg:

¥Wrapping any custom CSS with @layer also makes it possible to use modifiers with those rules, like hover: and focus: or responsive modifiers like md: and lg:.

@apply

使用 @apply 将任何现有工具类内联到你自己的自定义 CSS 中。

¥Use @apply to inline any existing utility classes into your own custom CSS.

当你需要编写自定义 CSS(例如覆盖第三方库中的样式)但仍想使用你的设计标记并使用你在 HTML 中习惯使用的相同语法时,这很有用。

¥This is useful when you need to write custom CSS (like to override the styles in a third-party library) but still want to work with your design tokens and use the same syntax you’re used to using in your HTML.

.select2-dropdown {
  @apply rounded-b-lg shadow-md;
}
.select2-search {
  @apply border border-gray-300 rounded;
}
.select2-results__group {
  @apply text-lg font-bold text-gray-900;
}

默认情况下,任何与 @apply 内联的规则都将删除 !important,以避免特殊性问题:

¥Any rules inlined with @apply will have !important removed by default to avoid specificity issues:

/* Input */
.foo {
  color: blue !important;
}

.bar {
  @apply foo;
}

/* Output */
.foo {
  color: blue !important;
}

.bar {
  color: blue;
}

如果你想 @apply 现有类并将其变为 !important,只需将 !important 添加到声明的末尾:

¥If you’d like to @apply an existing class and make it !important, simply add !important to the end of the declaration:

/* 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;
}

请注意,如果你使用的是 Sass/SCSS,则需要使用 Sass 的插值功能才能使其正常工作:

¥Note that if you’re using Sass/SCSS, you’ll need to use Sass’ interpolation feature to get this to work:

.btn {
  @apply font-bold py-2 px-4 rounded #{!important};
}

将 @apply 与每个组件的 CSS 一起使用

¥Using @apply with per-component CSS

Vue 和 Svelte 等组件框架支持在每个组件文件中的 <style> 块中添加每个组件的样式。

¥Component frameworks like Vue and Svelte support adding per-component styles within a <style> block that lives in each component file.

如果你尝试在这些每个组件 <style> 块之一中对你在全局 CSS 中定义的自定义类进行 @apply,你将收到有关该类不存在的错误消息:

¥If you try to @apply a custom class you’ve defined in your global CSS in one of these per-component <style> blocks, you’ll get an error about the class not existing:

main.css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .card {
    background-color: theme(colors.white);
    border-radius: theme(borderRadius.lg);
    padding: theme(spacing.6);
    box-shadow: theme(boxShadow.xl);
  }
}
Card.svelte
<div>
  <slot></slot>
</div>

<style>
  div {
    /* Won't work because this file and main.css are processed separately */
    @apply card;
  }
</style>

这是因为在幕后,像 Vue 和 Svelte 这样的框架正在独立处理每个 <style> 块,并针对每个块单独运行 PostCSS 插件链。

¥This is because under-the-hood, frameworks like Vue and Svelte are processing every single <style> block independently, and running your PostCSS plugin chain against each one in isolation.

这意味着如果你有 10 个组件,每个组件都有一个 <style> 块,Tailwind 将单独运行 10 次,并且每次运行对其他运行的了解为零。因此,当你尝试在 Card.svelte 中执行 @apply card 时,它会失败,因为 Tailwind 不知道 card 类的存在,因为 Svelte 完全隔离地处理 Card.sveltemain.css

¥That means if you have 10 components that each have a <style> block, Tailwind is being run 10 separate times, and each run has zero knowledge about the other runs. Because of this, when you try to @apply card in Card.svelte it fails, because Tailwind has no idea that the card class exists since Svelte processed Card.svelte and main.css in total isolation from each other.

这个问题的解决方案是使用 插件系统 在组件中定义任何你想要 @apply 的自定义样式:

¥The solution to this problem is to define any custom styles you want to @apply in your components using the plugin system instead:

tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  // ...
  plugins: [
    plugin(function ({ addComponents, theme }) {
      addComponents({
        '.card': {
          backgroundColor: theme('colors.white'),
          borderRadius: theme('borderRadius.lg'),
          padding: theme('spacing.6'),
          boxShadow: theme('boxShadow.xl'),
        }
      })
    })
  ]
}

这样,Tailwind 处理的任何使用此配置文件的文件都可以访问这些样式。

¥This way any file processed by Tailwind that uses this config file will have access to those styles.

老实说,最好的解决办法就是根本不做这种奇怪的事情。按照预期的方式在你的标记中直接使用 Tailwind 的工具,并且不要滥用 @apply 功能来执行此类操作,你将获得更好的体验。

¥Honestly though the best solution is to just not do weird stuff like this at all. Use Tailwind’s utilities directly in your markup the way they are intended to be used, and don’t abuse the @apply feature to do things like this and you will have a much better experience.

@config

使用 @config 指令指定 Tailwind 在编译该 CSS 文件时应使用哪个配置文件。这对于需要为不同的 CSS 入口点使用不同的配置文件的项目很有用。

¥Use the @config directive to specify which config file Tailwind should use when compiling that CSS file. This is useful for projects that need to use different configuration files for different CSS entry points.

@config "./tailwind.site.config.js";

@tailwind base;
@tailwind components;
@tailwind utilities;

你提供给 @config 指令的路径是相对于该 CSS 文件的,并且将优先于 PostCSS 配置或 Tailwind CLI 中定义的路径。

¥The path you provide to the @config directive is relative to that CSS file, and will take precedence over a path defined in your PostCSS configuration or in the Tailwind CLI.

请注意,如果你使用的是 postcss-import,则 @import 语句需要出现在 @config 之前才能正常工作,因为 postcss-import 严格遵守 CSS 规范,该规范要求 @import 语句位于文件中的任何其他规则之前。

¥Note that if you’re using postcss-import, your @import statements need to come before @config for things to work correctly, as postcss-import is strict about following the CSS spec which requires @import statements to precede any other rules in the file.

不要将 @config 放在 @import 语句之前

admin.css
@config "./tailwind.admin.config.js";

@import "tailwindcss/base";
@import "./custom-base.css";
@import "tailwindcss/components";
@import "./custom-components.css";
@import "tailwindcss/utilities";

@import 语句放在 @config 指令之前

admin.css
@import "tailwindcss/base";
@import "./custom-base.css";
@import "tailwindcss/components";
@import "./custom-components.css";
@import "tailwindcss/utilities";

@config "./tailwind.admin.config.js";

函数

¥Functions

Tailwind 添加了一些自定义函数,你可以在 CSS 中使用这些函数来访问特定于 Tailwind 的值。这些函数在构建时进行评估,并在最终 CSS 中被静态值替换。

¥Tailwind adds a few custom functions you can use in your CSS to access Tailwind-specific values. These functions are evaluated at build-time, and are replaced by static values in your final CSS.

theme()

使用 theme() 函数通过点表示法访问你的 Tailwind 配置值。

¥Use the theme() function to access your Tailwind config values using dot notation.

.content-area {
  height: calc(100vh - theme(spacing.12));
}

如果你需要访问包含点的值(如间距比例中的 2.5 值),你可以使用方括号表示法:

¥If you need to access a value that contains a dot (like the 2.5 value in the spacing scale), you can use square bracket notation:

.content-area {
  height: calc(100vh - theme(spacing[2.5]));
}

由于 Tailwind 使用 嵌套对象语法 来定义其默认调色板,因此请确保使用点符号来访问嵌套颜色。

¥Since Tailwind uses a nested object syntax to define its default color palette, make sure to use dot notation to access the nested colors.

访问嵌套颜色值时不要使用破折号语法

.btn-blue {
  background-color: theme(colors.blue-500);
}

使用点表示法访问嵌套颜色值

.btn-blue {
  background-color: theme(colors.blue.500);
}

要调整使用 theme 检索到的颜色的透明度,请使用斜杠后跟你要使用的透明度值:

¥To adjust the opacity of a color retrieved with theme, use a slash followed by the opacity value you want to use:

.btn-blue {
  background-color: theme(colors.blue.500 / 75%);
}

screen()

screen 函数允许你创建按名称引用断点的媒体查询,而不是在你自己的 CSS 中复制它们的值。

¥The screen function allows you to create media queries that reference your breakpoints by name instead of duplicating their values in your own CSS.

@media screen(sm) {
  /* ... */
}

这将在构建时解析为底层屏幕值,生成与指定断点匹配的常规媒体查询:

¥This will resolve to the underlying screen value at build-time, generating a regular media query that matches specified breakpoint:

@media (min-width: 640px) {
  /* ... */
}