# 函数和指令

参考文档地址 (opens new window)

# 1. @layer

使用 @layer 指令告诉 Tailwind 一组自定义样式应该属于哪个 “bucket”。可用的层有 base, components 和 utilities。

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

/*添加基础样式,可以重置tailwind的样式
通过使用 @layer 指令,Tailwind 将自动将这些样式移到 @tailwind base 的同一位置,以避免出现一些意外问题。*/
@layer base {
  h1 {
    @apply text-2xl;
  }

  h2 {
    @apply text-xl;
  }
}
/*Tailwind 会将这些样式自动移到与 @tailwind components 相同的位置,因此您不必担心在源文件中正确放置顺序。
使用 @layer 指令还将指示 Tailwind 在清除 components 层时考虑使用哪些样式进行清除。*/
@layer components {
  .btn-blue {
    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
  }
}

/*添加新的功能类*/
@layer utilities {
  @variants hover, focus {
    .filter-none {
      filter: none;
    }

    .filter-grayscale {
      filter: grayscale(100%);
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# 2. @apply

使用 @apply 将任何现存的功能类内联到您的自定义 CSS 中。

当您在您的 HTML 里找到您想要提取到一个新组件的通用的功能模式时,这非常有用。

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

.btn-blue {
  @apply bg-blue-500 hover:bg-blue-700 text-white;
}
1
2
3
4
5
6
7

# !important

如果您想使用 @apply 内联一个已经存在的类,并且为其设置 !important,只需要把 !important 添加到声明的结尾即可。

注意,类是根据其在原始 CSS 中的位置而不是根据在 @apply 指令之后列出它们的顺序来应用的。这是为了确保使用 @apply 提取类列表时得到的行为与直接在 HTML 中列出的类的行为相匹配。

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

/* 输出这样的css */
.btn {
  font-weight: 700 !important;
  padding-top: 0.5rem !important;
  padding-bottom: 0.5rem !important;
  padding-right: 1rem !important;
  padding-left: 1rem !important;
  border-radius: 0.25rem !important;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

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

.btn {
@apply font-bold py-2 px-4 rounded #{!important};
}
1
2
3
更新时间: 2024/7/30 17:14:28