Extending Tailwind with Responsive Custom Utility Classes

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson, we discover how to generate custom utility classes that follow Tailwind’s mobile-first, responsive naming convention pattern, using the 'variants' PostCSS directive.

Instructor: [00:00] Here are two custom class names that apply fancy background gradients. Currently, these styles cannot respond to state or screen size. They're always the same. What if I wanted the blue gradient to become orange on hover, and vice versa for the other element?

[00:17] With Tailwind classes, I'd go hover, BG gradient orange, and the blue equivalent for the other one, but here nothing will happen, because it's regular CSS. Here's the cool thing, Tailwind lets you easily create variants with the at variants directive. Let's do an at variant block, and we'll request the hover variant.

[00:40] Now, our custom CSS will also generate hover state variants just like that. If we look at the compiled CSS, we can see that Tailwind generated the variants for us following the naming convention and place. This is pretty cool.

[00:56] Let's also make some responsive variants. I want to flip the background colors on bigger screens. I'll change hover to MD here to target the medium breakpoint. We'll add responsive to the variant block to generate responsive classes. How cool is that?

[01:17] Other types of available variants are focus and group hover. As you might notice, these four variants are the same than the option that we can pass to each module in the Tailwind config file. This means you can write custom utility classes and seamlessly integrate them with your Tailwind utilities.