csstailwind-csstailwind-css-4

Tailwind @apply doesn't work with @layer base and @layer components anymore in v4


Docs says in v4 base and components layers are still defined with @layer base and @layer components, also in v3 classes defined like that could be used with @apply. The problem is they fail in v4.

https://tailwindcss.com/docs/adding-custom-styles#adding-base-styles

Practically it means I am forced to define all base, components and utilities layers with @utility to be able to use those classes with @apply which of course would create a big mess.

I could define all layers with @utility and then set layers in @import statement but that also doesn't look too nice.

@import "tailwindcss/theme.css" layer(theme);
@import "tailwindcss/base.css" layer(base);
@import "tailwindcss/components.css" layer(components);
@import "tailwindcss/utilities.css" layer(utilities);

So at the end how to do this in v4? I already have a lot of code that uses custom classes with @apply defined in base and components layers and now in v4 they produce Cannot apply unknown utility class. On the other hand I dont want to define base and components as utilities.

I saw similar Github issues without obvious solution. If I use @reference I get @custom-variant cannot be nested. and @utility cannot be nested..

https://github.com/tailwindlabs/tailwindcss/discussions/16429

https://github.com/tailwindlabs/tailwindcss/discussions/13336

You can see my styles code here:

https://github.com/nemanjam/nemanjam.github.io/tree/feat/tailwind4-v2/src/styles


Solution

  • In v4, Tailwind doesn't "hijack" the @layer at-rule anymore.

    On the other hand I dont want to define base and components as utilities.

    You'd need to use @utility to let Tailwind know about class names and thus be able to use them with @apply.

    You can use @layer inside @utility to place them in the appropriate cascade layer, like:

    @utility foo {
      @layer base {
        …
      }
    }
    

    Ideally, you'd use your templates to define the components, instead of writing any CSS. Adam Wathan (creator of Tailwind) does seem to advocate avoiding @apply: