csstailwind-csscss-layer

CSS rule not applied if inside @layer because of purge?


I notice sometimes random classes not working inside @layer base or @layer components but working if I'm putting it outside of everything.

For example I spent hours trying to understand why this style wasn't applied (not compiled in final CSS):

@layer base {
    .input-group{
        @apply mb-16;
    }
}

But if I put it outside of the @layer, then it works. There is absolutely no reason as .input-group is not used by anything else.

I believe this is due to purge or something: this style is not called in my HTML, I call it through a WordPress block, so it's injected directly while loading the page.

If my thought is true, is there a way to prevent it? I don't think I should completely disable the purge.

I have a similar issue when I call some classes directly from wordpress blocks, that were not used previously : they're not part of the CSS build.


Solution

  • As per the documentation:

    Removing unused custom CSS

    Any custom styles you add to the base, components, or utilities layers will only be included in your compiled CSS if those styles are actually used in your HTML.

    main.css

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    @layer components {
      /* This won't be included in your compiled CSS unless you actually use it */
      .card {
        /* ... */
      }
    }
    

    If you want to add some custom CSS that should always be included, add it to your stylesheet without using the @layer directive:

    main.css

    @tailwind base;
    @tailwind components;
    
    /* This will always be included in your compiled CSS */
    .card {
      /* ... */
    }
    
    @tailwind utilities;
    

    Make sure to put your custom styles where they need to go to get the precedence behavior you want. In the example above, we’ve added the .card class before @tailwind utilities to make sure utilities can still override it.

    So for your rule, you could consider having it outside any @layer, like:

    @tailwind base;
    
    .input-group{
      @apply mb-16;
    }
    
    @tailwind components;
    @tailwind utilities;
    

    Alternatively, you could safelist the classes:

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      safelist: [
        'input-group',
      ]
      // …
    }
    

    As an aside, you may also wish to avoid @apply altogether as recommended by Adam Wathan, creator of Tailwind: