简体   繁体   中英

hover OR focus in Tailwind CSS

So I want to change the color of the text on hover or focus

<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. I tried the code below, but it becomes an and statement instead of 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:

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

Is that possible in TailwindCSS?

You may write a simple plugin to combine focus and hover into one custom variant as described in the documentation.

The key is that addVariant() allows passing in multiple selectors as rules in the second parameter:

//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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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