Tailwind - css rule is invisible if I use layer

2.4k views Asked by At

Do you have any ideas why @layer in Tailwind CSS doesn't work?

If I write in my styles.css for example

h1 {
  @apply text-2xl;
}

it works but if I do:

@layer base {
  h1 {
    @apply text-2xl;
  }
}

it doesn't. It just doesn't see this style.

2

There are 2 answers

1
Matt On

It's possible that your h1 style is getting purged by Tailwind's styler purging process: https://tailwindcss.com/docs/controlling-file-size:

Using the @layer directive will also instruct Tailwind to consider those styles for purging when purging the layer.

Since, presumably, you're not referencing the h1 style with @apply, maybe Tailwind is considering the style unused. Although, one would hope that Tailwind would not purge a tag-based selector.

Take a look at the CSS file that is built, either on the file system or inspector in the browser, and look for your h1 styles.

From the Tailwind docs, maybe try adding h1 to your whitelist - although I don't think it will work since the whitelist seems to want class-based selectors.

// tailwind.config.js
module.exports = {
  purge: {
    content: ['./src/**/*.html'],

    // These options are passed through directly to PurgeCSS
    options: {
      whitelist: ['bg-red-500', 'px-4'],
    }
  },
  // ...
}

I recommend asking if tag selectors work with layers on the Tailwind Discord or forum: https://tailwindcss.com/community

0
Dot Simplify On

I have got same error but i figured out from inspecting elements that inherited styles have been applied then i add some more styles to strong elements then mounted css styles have more precedence because of selectors and it worked..

@layer base {
    h1 {    
        @apply text-green-600 font-bold text-4xl;
    }  strong {
        @apply text-gray-800 font-extrabold text-2xl;
    }
}