Tailwind CSS Hocus Plugin

A few days after adding this snippet, I published this plugin as an npm package which you can now find under the name tailwindcss-hocus, and on GitHub here.

A plugin that's great for lazy people like me who make their :hover and :focus states basically they same. As anyone who's used Tailwind CSS for a while might expect, it adds the hocus: variant which will add the specificd class on hover and focus. It also adds hocus-within, group-hocus, and group-hocus-within which are similar but based of slightly different existing variants.

tailwind.config.js
javascript
const plugin = require('tailwindcss/plugin')
 
const hocusPlugin = plugin(({ addVariant }) => {
  addVariant('hocus', ['&:hover', '&:focus'])
  addVariant('hocus-within', ['&:hover', '&:focus-within'])
  addVariant('group-hocus', [
    ':merge(.group):hover &',
    ':merge(.group):focus &',
  ])
  addVariant('group-hocus-within', [
    ':merge(.group):hover &',
    ':merge(.group):focus-within &',
  ])
})
 
/**
 * @type {import('tailwindcss').Config}
 */
module.exports = {
  // ...the rest of your config
  plugins: [hocusPlugin],
}

Usage & CSS Output Example

To use this plugin, you use it like any other variant - prefix an existing Tailwind class with hocus: or one of the other variants:

high-quality-code.html
html
<button className="hocus:text-red-700">Click Me!</button>

Here's what the Tailwind compiler outputs for the HTML above:

output-styles.css
css
.hocus\:text-red-700:hover,
.hocus\:text-red-700:focus {
  --tw-text-opacity: 1;
  color: rgb(185 28 28 / var(--tw-text-opacity));
}

Example

  • This website (in the past) - Inspect element on the link!

    Note: The latest version of the linked tailwind.config.js uses the npm package.

Created 19/09/22Updated 30/11/22
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here