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.
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:
https://twitter.com/adamwathan/status/1226511611592085504
Confession: The
apply
feature in Tailwind basically only exists to trick people who are put off by long lists of classes into trying the framework.You should almost never use it 😬
Reuse your utility-littered HTML instead.
https://twitter.com/adamwathan/status/1559250403547652097
I can say with absolute certainty that if I started Tailwind CSS over from scratch, there would be no
@apply
😬The behavior is outrageously complicated, everyone struggles to build the right mental model of what it's supposed to do, and it encourages bad CSS architecture.