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 Tailwind CSS?
In Tailwind 4, you can use @custom-variant to achieve this effect:
<script src="https://unpkg.com/@tailwindcss/browser@4"></script>
<input class="hocus:text-green-500" value="foo bar" />
<style type="text/tailwindcss">
@custom-variant hocus (&:hover, &:focus);
</style>
DEMO on tailwind play.
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 = {
plugins: [
tailwind.plugin(function({ addVariant }) {
addVariant('hocus', ['&:hover', '&:focus'])
}),
],
}
<script src="https://cdn.tailwindcss.com/3.4.5"></script>
<input class="hocus:text-green-500" value="foo bar" />
DEMO on tailwind play
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With