Add Custom Utilities with TailwindCSS

Daniel Wentsch
1 min readDec 30, 2020

--

Screenshot of a custom utility defined with TailwindCSS variants directive

Sometimes I need some CSS that’s not included with Tailwind. CSS filters are a simple example. Instead of coming up with component names, adding and importing partials, we can opt into building atomic utilities that can be composed into any other component that requires such functionality.

This is a great use case for Tailwind’s @variants directive.

Say we want to desaturate gallery thumbnails using filter: grayscale(100%) and show the coloured version on hover. Instead of writing the styles only for something highly specific such as .gallery__thumbnail { ... } I recommend adding a file called utilities/filters.[s]css:

@variants hover, focus, responsive {
.grayscale {
filter: grayscale(100%);
}

.filter-reset {
filter: none;
}
}

This will create those utilities together with all the variants we specified. So say we want our grayscale filter on an element but only starting at the md breakpoint and bring the color back on focus and hover. Oh, and a little transition would be nice, too. We can easily compose this as follows:

<img class="md:grayscale md:hover:filter-reset md:focus:filter-reset transition-all duration-200 ease-in" />

Links

Originally published at https://wentsch.me on December 30, 2020.

--

--

Daniel Wentsch
Daniel Wentsch

Written by Daniel Wentsch

I’m a freelance designer & developer from Freiburg, Germany. I write about capturing, collecting, and curating ideas—plus other things that spark my curiosity.

No responses yet