I am working on a Next.js project using Tailwind CSS with JIT mode enabled. I’ve encountered an issue where custom utility classes defined inside the @layer utilities block in my theme.css file are not being compiled and applied as expected. However, when these classes are defined outside the @layer directive, they work correctly.
theme.css (Not working)
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer utilities {
.h1-bold {
@apply text-[30px] font-bold leading-[42px] tracking-tighter;
}
}
theme.css (Working)
@tailwind base;
@tailwind components;
@tailwind utilities;
.h1-bold {
@apply text-[30px] font-bold leading-[42px] tracking-tighter;
}
globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@import url("../styles/theme.css");
body {
font-family: "Inter", sans-serif;
}
I’m new to Next.JS and tailwind. Could someone point me to the right direction? why Tailwind CSS’s JIT mode is not processing classes inside the @layer directive as expected in this scenario? Is there a specific configuration or project setup that I might be missing?
Observed behavior:
When .h1-bold is inside @layer utilities, the styles seem to revert to default browser styles (like font-size: inherit; font-weight: inherit;). But when defined outside @layer utilities, the custom styles are applied correctly.
Expected behavior:
Custom utility classes defined inside @layer utilities should be compiled and applied by Tailwind’s JIT compiler.
2
Answers
I figure it out. Turns out it was all a mismanagement of the imports in the layout.tsx.
If you don't have an _app.js/ts file you need to handle the imports directly in the layout.tsx
I know I'm dumb.
Custom utility classes will only appear in the compiled CSS if Tailwind has found a unbroken string in files covered by the
content
file globs orsafelist
that matches the class name. Consider checking you haveh1-bold
in a file covered by thecontent
file globs.They should not. It is the browser’s job to apply CSS rules to the right elements. Tailwind only generates the CSS rules.
Depending on Next.js’s CSS processing rules, you may also need to configure build-time imports with
postcss-import
. This would precipitate some changes to your CSS structure: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
https://twitter.com/adamwathan/status/1559250403547652097