0PricingLogin
Tailwind CSS Academy · Lesson

Adding Custom Variants via Plugin

Create custom state variants with addVariant to target selectors like .is-active or data attributes, and use them as class prefixes in markup.

What Are Tailwind Variants?

Tailwind variants are the prefixes like hover:, focus:, dark:, and sm: that conditionally apply a utility class. Each variant wraps the generated CSS in a selector or media query. The addVariant plugin helper lets you register your own variant prefixes, enabling you to write things like aria-selected:bg-blue-100, data-active:opacity-100, or is-loading:cursor-wait in your HTML.

The addVariant Helper

addVariant takes two arguments: the variant name (the prefix before the colon) and a selector template string. The selector uses & as a placeholder for the generated class selector. When a user writes hocus:bg-gray-100, Tailwind replaces & with the generated class selector for bg-gray-100 and wraps it in your selector pattern.

const plugin = require('tailwindcss/plugin');

plugin(function({ addVariant }) {
  // 'hocus' = hover OR focus (useful for touch/keyboard parity)
  addVariant('hocus', ['&:hover', '&:focus']);

  // Usage in markup:
  // <button class='hocus:bg-blue-100 hocus:text-blue-700'>
  //   This button highlights on both hover and focus
  // </button>
})

All lessons in this course

  1. The Tailwind Plugin API
  2. Adding Custom Utilities via Plugin
  3. Adding Custom Variants via Plugin
  4. Publishing and Reusing Plugins
← Back to Tailwind CSS Academy