简体   繁体   English

hover 或关注 Tailwind CSS

[英]hover OR focus in Tailwind CSS

So I want to change the color of the text on hover or focus所以我想更改hoverfocus上的文本颜色

<div class="hover:text-green-500 focus:text-green-500">foo bar</div>

But I was wondering if is possible to compress all in one statement, so I would not need to repeat the text-green-500 for both.但我想知道是否可以在一个语句中压缩所有内容,所以我不需要为两者重复text-green-500 I tried the code below, but it becomes an and statement instead of or .我尝试了下面的代码,但它变成了一个and语句而不是or

<div class="hover:focus:text-green-500">foo bar</div>

In pure css, what I'm looking for to do would be something like this:在纯 css 中,我想要做的是这样的:

div:hover, div:focus {
  color: green
}

Is that possible in TailwindCSS?这在 TailwindCSS 中可能吗?

You may write a simple plugin to combine focus and hover into one custom variant as described in the documentation.您可以编写一个简单的插件来将焦点和 hover 组合成一个自定义变体,如文档中所述。

The key is that addVariant() allows passing in multiple selectors as rules in the second parameter:关键是addVariant()允许在第二个参数中作为规则传入多个选择器:

//tailwind.config.js

const plugin = require('tailwindcss/plugin')

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

usage:用法:

<div class="hocus:text-green-500">foo bar</div>

DEMO on tailwind play顺风游戏演示

You can @apply to re-use existing tailwind styles so that you don't end-up writing color: green or whatever extra you would otherwise be writing in plain CSS>您可以@apply重新使用现有的 tailwind styles ,这样您就不会最终编写color: green或您本来可以用普通 CSS 编写的任何其他内容>

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

div:hover, div:focus {
  @apply text-green-500;
}

This way, you will also end up having less code in your class attribute.这样,您的class属性中的代码也将减少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM