Get introduced to CSS units and learn how to define classes by adding prefixes.

We have to learn one more unique feature before we get to more utility classes. It’s common to want objects to display differently when the user drags a mouse over them, which corresponds to the CSS pseudo-class hover.

Define CSS classes by adding prefixes

In Tailwind, we can define most CSS pseudo-classes by adding prefixes to other Tailwind utilities. If we want an anchor tag to have an underline when we hover the mouse over it, we can use the following command:

<a class="hover:underline">Keep your face to the sunshine.</a>

That’s compact, reasonably straightforward to read, and defined along with the HTML, so it’s clear when it applies. We can use hover: with any Tailwind utility.

Tailwind also uses prefixes to allow different utilities to be invoked based on the width of the screen, so that we can write class="sm:m-2 lg:m-4, and our element will grow a bigger margin as the screen gets wider.

There’s one complication. While we can write a hover: prefix to any Tailwind utility, by default, it only generates the prefixed utilities for certain CSS properties. Conveniently for us, text decoration, which covers underlining, is one of those.

We’ll look at how to turn on the prefixes for other properties and for other prefixes. Tailwind defines over a dozen prefixes. However, we have to turn on the ones we need explicitly.

We can even use the prefixes in conjunction with @apply. So @apply hover:underline is legal to define a new CSS class.

Note: We’ll use text with different sizes in the following playground, and the text is underlined when we hover over it.

Get hands-on with 1200+ tech skills courses.