You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Tailwind CSS v4的@variant规则进行分组?

在Tailwind CSS v4中组合变体的正确方式

在Tailwind CSS v4.2及目前的稳定版本中,无法直接在单个@variant规则里通过:拼接多个变体(比如@variant hover:not-focus这种写法是不生效的)。官方设计的@variant语法要求每个变体单独声明,组合变体需要通过嵌套@variant来实现层级,这和工具类里hover:not-focus:bg-sky-900的结构一一对应。

标准嵌套写法(官方推荐)

要实现hover:not-focus的效果,必须使用嵌套的@variant规则,这是当前版本下的正确方式:

<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.2"></script>
<style type="text/tailwindcss">
.example {
  width: --spacing(32);
  height: --spacing(32);
  background-color: var(--color-sky-300);
  
  @variant hover {
    @variant not-focus {
      background-color: var(--color-sky-900);
    }
  }
}
</style>
<input class="example">

替代方案:直接使用原生CSS选择器

如果觉得嵌套@variant不够简洁,也可以跳过@variant,直接用原生CSS的复合选择器来写,效果完全一致:

<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.2"></script>
<style type="text/tailwindcss">
.example {
  width: --spacing(32);
  height: --spacing(32);
  background-color: var(--color-sky-300);
}

.example:hover:not(:focus) {
  background-color: var(--color-sky-900);
}
</style>
<input class="example">

进阶:自定义可复用的组合变体

如果需要在多个地方复用这种组合变体,可以在Tailwind配置中自定义一个新变体,这样就能像原生变体一样使用:

// tailwind.config.js
export default {
  plugins: [
    function({ addVariant }) {
      // 定义hover-not-focus变体
      addVariant('hover-not-focus', '&:hover:not(:focus)');
    }
  ]
}

之后就可以在@apply或工具类中直接使用:

.example {
  @apply size-32 bg-sky-300 hover-not-focus:bg-sky-900;
}

内容的提问来源于stack exchange,提问作者rozsazoltan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 20:33:13