Skip to content

变体

¥Variants

变体 允许你对现有规则应用一些变体,例如 Tailwind CSS 的 hover: 变体。

¥Variants allow you to apply some variations to your existing rules, like the hover: variant from Tailwind CSS.

示例

¥Example

ts
variants: [
  // hover:
  (matcher) => {
    if (!matcher.startsWith('hover:'))
      return matcher
    return {
      // slice `hover:` prefix and passed to the next variants and rules
      matcher: matcher.slice(6),
      selector: s => `${s}:hover`,
    }
  },
],
rules: [
  [/^m-(\d)$/, ([, d]) => ({ margin: `${d / 4}rem` })],
]
  • matcher 控制何时启用变体。如果返回值为字符串,则将其作为匹配规则的选择器。

    ¥matcher controls when the variant is enabled. If the return value is a string, it will be used as the selector for matching the rules.

  • selector 提供了自定义生成的 CSS 选择器的可用性。

    ¥selector provides the availability of customizing the generated CSS selector.

在引擎盖下

¥Under the hood

让我们看一下匹配 hover:m-2 时发生的情况:

¥Let's have a tour of what happened when matching for hover:m-2:

  • hover:m-2 是从用户使用情况中提取的

    ¥hover:m-2 is extracted from users usages

  • hover:m-2 发送到所有变体进行匹配

    ¥hover:m-2 send to all variants for matching

  • hover:m-2 与我们的变体匹配并返回 m-2

    ¥hover:m-2 is matched by our variant and returns m-2

  • 结果 m-2 将用于下一轮变体匹配

    ¥the result m-2 will be used for the next round of variants matching

  • 如果没有其他变体匹配,则 m-2 将去匹配规则

    ¥if no other variant is matched, m-2 will then goes to match the rules

  • 我们的第一条规则匹配并生成 .m-2 { margin: 0.5rem; }

    ¥our first rule get matched and generates .m-2 { margin: 0.5rem; }

  • 最后,我们将变体的转换应用于生成的 CSS。在本例中,我们将 :hover 添加到 selector 钩子之前

    ¥finally, we apply our variants' transformation to the generated CSS. In this case, we prepended :hover to the selector hook

结果,将生成以下 CSS:

¥As a result, the following CSS will be generated:

css
.hover\:m-2:hover { margin: 0.5rem; }

这样,我们就可以仅当用户将鼠标悬停在元素上时应用 m-2

¥With this, we could have m-2 applied only when users hover over the element.

更进一步

¥Going further

变体系统非常强大,本指南无法全面介绍,你可以查看 默认预设的实现 以了解更多高级用法。

¥The variant system is very powerful and can't be covered fully in this guide, you can check the default preset's implementation to see more advanced usages.