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 the exact 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" />
Top comments (0)