Skip to content

Things read, heard, watched and found. Now and then a thought of my own.

Timeline

Post 1 min read

Add Custom Utilities with TailwindCSS

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.

A letter every Monday

The week’s reading, highlights and the odd thought of my own, in one email.

One email a week. Unsubscribe with one click. See a sample