在 Tailwind CSS 中悬停或聚焦

Ed.*_*.an 5 html css tailwind-css

所以我想改变或上的文字颜色hover focus

<div class="hover:text-green-500 focus:text-green-500">foo bar</div>
Run Code Online (Sandbox Code Playgroud)

但我想知道是否可以将所有内容压缩在一个语句中,这样我就不需要text-green-500对两者重复。我尝试了下面的代码,但它变成了and语句而不是or

<div class="hover:focus:text-green-500">foo bar</div>
Run Code Online (Sandbox Code Playgroud)

在纯CSS中,我想要做的事情是这样的:

div:hover, div:focus {
  color: green
}
Run Code Online (Sandbox Code Playgroud)

这在 TailwindCSS 中可能吗?

Kar*_* Jo 14

您可以编写一个简单的插件,将焦点和悬停合并到一个 自定义变体中,如文档中所述。

关键是addVariant()允许在第二个参数中传入多个选择器作为规则:

//tailwind.config.js

const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addVariant }) {
      addVariant('hocus', ['&:hover', '&:focus'])
    })
  ],
}
Run Code Online (Sandbox Code Playgroud)

用法:

<div class="hocus:text-green-500">foo bar</div>
Run Code Online (Sandbox Code Playgroud)

顺风游戏演示


Jav*_*cal 0

您可以@apply重复使用现有的顺风样式,这样您就不会最终编写color: green或使用纯CSS>编写的任何额外内容>

https://tailwindcss.com/docs/functions-and-directives#apply

div:hover, div:focus {
  @apply text-green-500;
}
Run Code Online (Sandbox Code Playgroud)

这样,您的属性中的代码最终也会减少class