DEV Community

Ben Sinclair
Ben Sinclair

Posted on

The (Tailwind) Purge

This is the first in a series1 of things I've banged my head over in daily agency work, as a full-stack body, or tbh whatever I'm employed as at the time. In agencies you tend to get sold to clients as everything from Software Architect to UX designer to DB admin depending on who's paying.

And anyone here who's ever had a conversation with me about, I don't know, chimneys or breakfast cereal or whatever, will know how I feel about Tailwind.

So say I have two pages, one of which (I'll call it "About") includes something like this:

<div class="grid grid-cols-5">
  <div class="col-span-5 lg:col-span-3">
Enter fullscreen mode Exit fullscreen mode

and the other (I'll call it, uh, "Babout") has this:

<div class="grid grid-cols-5">
  <div class={`col-span-${data.image ? 5 : 3}`}>
Enter fullscreen mode Exit fullscreen mode

The idea being that if my Babout page has an image, then that column should take up the full width, otherwise it should take up less space to make room for the upcoming cat picture. Seems fine to me. Works.

And if I unpublish the About page, the Babout page stops styling its grid at all.

Why's that? Well, it's because Tailwind purges its CSS rules so you don't download every possible permutation of things like lg:p:mx-5. If you generated all of them there'd be more rules than grains of salt on a fish supper. That's because utility-class frameworks are a really bad idea, but I digress.

Why does purging the CSS break the poor Babout page? Because the purge is done by scraping the source files for all possible rule matches. That means that if you have a blog page talking about your shiny new Mazda MX-5, hey, now Tailwind includes the mx-5 rule regardless of whether you use it. Neato.

Other frameworks scrape the source, too, for things like annotations in comments (Symfony, anyone?). Those are also really bad ideas, and I'm sorry but I can't stop this digression.

More importantly, it means that because it can't find col-span-3 or col-span-5 in the source any more, it doesn't bother with them, and the page breaks.

The solutions are simple when you know them:

  1. use ${data.image ? 'col-span-5' : 'col-span-3'} instead
  2. add col-span-3 and col-span-5 to tailwind's "safelist"

But they're not simple when you don't know them.

Yes, this is touched on in the Tailwind documentation, but it's buried under the sand.

It's magic, magic baby. Front-end frameworks are especially fond of magic, and users will always get tripped-up by this sort of thing. I was, and it took an hour or more of digging and trying things out for me to figure what was going on.


  1. Maybe. I don't have a great record for sticking to resolutions. 

Top comments (0)