tailwindcss - 函数和指令

222 阅读2分钟

指令

@tailwind

使用 @tailwind 指令将 Tailwind 的 base 、 components 、 utilities 和 variants 样式插入到CSS中。

@layer

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

@apply

自定义 CSS,而且想要使用 tailwind 语法

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

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

.bar {
  @apply foo;
}

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

.bar {
  color: blue;
}

如果你想 @apply 一个现有的类,并使其成为 !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;
}

使用的是Sass/SCSS,则需要使用Sass的插值功能才能使其工作

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

单组件使用 @apply

在每个组件的 <style> 中使用你在全局CSS中定义的 @apply 自定义 class,你会得到一个关于 class 不存在的错误

@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);
  }
}
<div>
  <slot></slot>
</div>

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

使用插件在组件中定义任何你想要的自定义样式

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'),
        }
      })
    })
  ]
}

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

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

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

使用 postcss-import,将 @import 语句放在 @config 指令之前

函数

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

theme()

使用 theme() 函数以点表示法访问 Tailwind 配置值。

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

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

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

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

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

使用 theme 颜色不透明度,请使用斜线

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

screen()

screen 函数允许你创建媒体查询,通过名称引用你的断点

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