Declaring Variants

Learn about how to change the variants.

Changing the set of variants

The easiest way to change the set of variants for any core plug-in is to write out the entire list of the variants we want for the core plugin. For example, alternating row patterns can be applied with the odd or even property. Here, we want the odd and even variants for the background color:

module.exports = {
  variants: {
    backgroundColor: [
      'responsive', 'dark', 'group-hover',
      'hover', 'focus', 'odd', 'even'
    ] 
  }
}

As written, this list overrides the existing list. It does not extend it, so we have included all the existing default values in the list.

Precedence of variants

The order of variants is important because utilities are generated in the order specified in this list. Because of the way CSS works, ordering means that the variants at the end of the list will supersede variants at the beginning of the list if both appear in the same element. So, as written, even:bg-color-gray-500, will take effect over hover:bg-color-gray-900. Because of this, we should order our variants carefully.

There is an exception to the precedence rule. Responsive variants are generated separately. Tailwind generates a complete set of other variants for each responsive variant, so we also have .sm:even:bg-color-gray-500, and so on.

We highly recommend explicitly including the entire list in our configuration. Tailwind does have utilities that allow us to add a single variant at a specific place in the existing list, but they seem overly complex and hard to read. We’ll stick with the array list.

Integrate with the existing CSS

One problem we might face if we use Tailwind in conjunction with existing CSS is a name conflict. Our existing CSS might already define hidden, flex-grow, or mx-64. Tailwind gives us a way to prevent this problem by offering us the ability to put a common prefix in front of all Tailwind utilities—prefix: "<SOMETHING>". If we declare prefix: "twind", all the Tailwind utilities are transformed. We end up with twind-hidden, twind-flex-grow, and even twind-mx-64. If we have a prefix, it attaches normally, as in hover:twind-text-black.

A different problem is that our existing CSS may be set up in such a way that all the existing CSS selectors have high specificity and thus override all of the Tailwind utilities. We can get around this with a configuration of important: true, which adds the CSS marker, !important, to all the Tailwind utilities. This should give them precedence over existing CSS. It can also have unwanted side effects if we use many different CSS libraries. Therefore, we have to be careful with it.

Some template tools do not allow us to use the colon (:) character in class names, making Tailwind’s prefixes illegal. We can specify a separator: option to choose our own separator, so separator: "--" means prefixes would look like hover--text-black or lg--m0-4.

Get hands-on with 1200+ tech skills courses.