tailwindcss: [v4] Cannot apply unknown utility class: xxx

Hello!

After upgrading from v3 to v4(via CLI), I encountered some error: Cannot apply unknown utility class: text-card-foreground.

This never happened in v3.

After some trial and error, I found that it seems necessary to import the main CSS file in my CSS.

Image Image

Is this the expected behavior? This will cause a large number of component styles to have issues.

Or, is there a trick for automatic import?

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 46
  • Comments: 76 (3 by maintainers)

Commits related to this issue

Most upvoted comments

After attempting migration, my app won’t start at all, instead I get console full of these errors warning about not being able to apply basic tailwind classes. I’m yet to figure out what goes wrong.

@apply is no longer global. You may need to use @reference.


As an aside, Adam Wathan (creator of Tailwind) does seem to advocate avoiding @apply:

You may not want to @import the main stylesheet again, as that will duplicate the Tailwind-generated CSS in the other file. You would use @reference instead.

just out of curiosity, why was v4 built this way that the global @apply doesn’t work anymore? i mean there has to be some reason for it I don’t understand yet

See #15778 (comment)

I think what would solve it better is some 1 line config that says which css file is the main one and boom. No need for explicit @reference. If necessary this could be simplified to something like @tailwind at the top of the file to tell it to reference the configured main file (this file wants to use tailwind). Think of something like main function in most compiled languages. There could only be 1 main function otherwise you will get compilation error. From what I see more and more people are confused with @reference. Adding some implicit way of referencing the exact same file would make it easier for people to migrate.

Several things:

1. Can’t resolve

I was initially getting:

Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
Error: Can't resolve '../app.scss' in '/path/to/project/src/scss'

And this is because Sass processes the files before Tailwind. Thus, the partials that have the @reference directives would already have been folded into editor-styles.scss or theme.scss.

Thus we should change the @reference path to be relative to their “main” file:

-@reference "../app.scss";
+@reference "./app.scss";

2. Cannot apply unknown utility class

Then, I was getting:

Error: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
Error: Cannot apply unknown utility class: hover:text-white-500

And this was because there was no white-500 value defined in the Tailwind configuration. Adding it in src/app.scss solved the problem:

 @import "tailwindcss";
+
+@theme {
+  --color-white-500: foo;
+}

After attempting migration, my app won’t start at all, instead I get console full of these errors warning about not being able to apply basic tailwind classes. I’m yet to figure out what goes wrong.

@philipp-spiess is it possible to specify path relative to the root dir? Problem with @reference is that sometimes you have ../../app.css sometimes ../../../app.css and sometimes ../../../../app.css and it’s hard to figure out the correct path with more complex directory structure. @reference "tailwindcss"; is easy to remember but it won’t work with cutomized theme. V3 didn’t have that problem and now I’m losing my mind with those relative paths. It would be helpful if we could for example specify path relative to package.json file or some other smarter solution. Why can’t we have some configuration that specifies “main”/“root” CSS file that is always going to be referenced?

@philipp-spiess I don’t have access to vite config inside angular project I tried to migrate to v4 unfortunately https://github.com/angular/angular-cli/issues/27695

For now v4 means dropping component styles completely. Adding @reference to 20 or more files with different relative paths is a hell I won’t go through.

Hey folks! We’ve just added a section on our upgrade guides that goes into more detail about the changed behavior for @apply.

To give further technical background, imagine a setup with two different Tailwind CSS configurations like this:

/* src/admin/index.css */
@theme {
  --color-primary: #fff;
}
/* src/app/index.css */
@theme {
  --color-primary: #000;
}

Since CSS modules, or <style> tags within .svelte, .vue, or .astro files are bundled separately for each page, they will go through your build tool as individual stylesheets with no reference to either of these configurations, so it’s inherently ambiguous which of these two CSS configuration files you want to refer to in these situations.

Let us know if you run into any other issues with this, thanks!

It seems you are missing @reference whereever you are using @apply. You’d need to add it in like so:

 <style scoped>
+@reference "tailwindcss/theme.css";
 @tailwind base;
 @layer base {

As an aside, Adam Wathan (creator of Tailwind) does seem to advocate avoiding @apply:

You probably need to use the @reference directive.

You could try using Subpath Imports like:

"imports": {
  "#app.css": "./path/to/app.css"
},
@reference "#app.css";

You can also do this in your .vue component:

<style scoped>
@reference "tailwindcss";
...
...
</style>
<style lang="postcss" scoped>
...
...
</style>

I agree 100% with @bugproof. A single line option would be awesome. Also using angular.

Same for me but not every time. It happens from time to time after migration.

Image

Image

If I remove the leading-6 then it throws error on the next class it finds

Can anyone guide me whats wrong with my code why and it is not forwarding the attributes

@import “tailwindcss”;

body { font-family: ‘General sans’, sans-serif; width: 100dvw; background-color: #dfdff0; overflow-x: hidden; }

@layer base { @font-face { font-family: “circular-web”; src: url(“/fonts/circularweb-book.woff2”) format(“woff2”); }

@font-face {
  font-family: "general";
  src: url("/fonts/general.woff2") format("woff2");
}

@font-face {
  font-family: "robert-medium";
  src: url("/fonts/robert-medium.woff2") format("woff2");
}

@font-face {
  font-family: "robert-regular";
  src: url("/fonts/robert-regular.woff2") format("woff2");
}

@font-face {
  font-family: "zentry";
  src: url("/fonts/zentry-regular.woff2") format("woff2");
}

}

@theme { –font-zentry: ‘zentry’, sans-serif; –font-general: ‘general’, sans-serif; –font-circular-web: ‘circular-web’, sans-serif; –font-robert-medium: ‘robert-medium’, sans-serif; –font-robert-regular: ‘robert-regular’, sans-serif;

--colors: {
  blue: {
    50: "#DFDFF0",
    75: "#dfdff2",
    100: "#F0F2FA",
    200: "#010101",
    300: "#4FB7DD",
  },
  violet: {
    300: "#5724ff",
  },
  yellow: {
    100: "#8e983f",
    300: "#edff66",
  }
}

}

@layer utilities { /* Add the custom-font class first */ .custom-font { @reference font-zentry; }

/* Then your existing utilities */
.border-hsla {
  @reference border border-white/20;
}

.nav-hover-btn {
  @reference relative ms-10 font-general text-xs uppercase text-blue-50 cursor-pointer;
}

/* Rest of your utility classes... */

} .border-hsla { @reference border border-white/20; }

.nav-hover-btn { @reference relative ms-10 font-general text-xs uppercase text-blue-50 cursor-pointer; }

.nav-hover-btn::after { @reference absolute -bottom-0.5 left-0 h-[2px] w-full origin-bottom-right scale-x-0 bg-neutral-800 transition-transform duration-300 ease-[cubic-bezier(0.65_0.05_0.36_1)] dark:bg-white; content: “”; }

.nav-hover-btn:hover::after { @reference origin-bottom-left scale-x-100; }

.floating-nav { @reference bg-black rounded-lg border; }

.absolute-center { @reference absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2; }

.flex-center { @reference flex justify-center items-center; }

.mask-clip-path { clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%); }

.special-font b { font-family: “Zentry”; font-feature-settings: “ss01” on; }

.hero-heading { @reference uppercase font-zentry font-black text-5xl sm:right-10 sm:text-7xl md:text-9xl lg:text-[12rem]; }

.about-subtext { @reference absolute bottom-[-80dvh] left-1/2 w-full max-w-96 -translate-x-1/2 text-center font-circular-web text-lg md:max-w-[34rem]; }

.about-image { @reference absolute left-1/2 top-0 z-20 h-[60vh] w-96 -translate-x-1/2 overflow-hidden rounded-3xl md:w-[30vw]; }

.animated-title { @reference flex flex-col gap-1 text-7xl uppercase leading-[.8] text-white sm:px-32 md:text-[6rem]; }

.animated-word { @reference special-font font-zentry font-black opacity-0; transform: translate3d(10px, 51px, -60px) rotateY(60deg) rotateX(-40deg); transform-origin: 50% 50% -150px !important; will-change: opacity, transform; }

.bento-tilt_1 { @reference relative border-hsla col-span-2 overflow-hidden rounded-md transition-transform duration-300 ease-out; }

.bento-tilt_2 { @reference relative col-span-1 row-span-1 overflow-hidden rounded-md transition-transform duration-300 ease-out; }

.bento-title { @reference uppercase text-4xl md:text-6xl font-black font-zentry; }

.story-img-container { @reference relative h-[90vh] md:h-dvh w-full; filter: url(“#flt_tag”); }

.story-img-mask { @reference absolute top-0 left-0 w-full h-full overflow-hidden md:left-[20%] md:top-[-10%] md:w-4/5 md:h-4/5; clip-path: polygon(4% 0, 83% 21%, 100% 73%, 0% 100%); }

.story-img-content { @reference absolute w-full h-[50dvh] md:h-dvh left-10 top-16 md:left-0 md:top-10 lg:left-[-300px] lg:top-[-100px] opacity-100; transform: translate3d(0, 0, 0) rotateX(0) rotateY(0) rotateZ(0) scale(1); }

.gallery-img-container { @reference w-64 h-64 overflow-hidden bg-violet-300; }

.gallery-img { @reference w-full h-full bg-cover; }

.gallery-img-4 { @reference sm:w-80 sm:h-80 md:h-96 md:w-[25rem] rounded-lg; }

.sword-man-clip-path { clip-path: polygon(16% 0, 89% 15%, 75% 100%, 0 97%); }

.contact-clip-path-1 { clip-path: polygon(25% 0%, 74% 0, 69% 64%, 34% 73%); }

.contact-clip-path-2 { clip-path: polygon(29% 15%, 85% 30%, 50% 100%, 10% 64%); }

/* Indicator Animation */ .indicator-line { @reference h-1 w-px rounded-full bg-white transition-all duration-200 ease-in-out; }

.indicator-line.active { animation: indicator-line 0.5s ease infinite; animation-delay: calc(var(–animation-order) * 0.1s); }

@keyframes indicator-line { 0% { height: 4px; transform: translateY(0px); } 50% { height: 16px; transform: translateY(-4px); } 100% { height: 4px; transform: translateY(0px); } }

/* Three-Body Loader (From Uiverse.io) */ .three-body { –uib-size: 35px; –uib-speed: 0.8s; –uib-color: #5d3fd3; position: relative; display: inline-block; height: var(–uib-size); width: var(–uib-size); animation: spin78236 calc(var(–uib-speed) * 2.5) infinite linear; }

.three-body__dot { position: absolute; height: 100%; width: 30%; }

.three-body__dot:after { content: “”; position: absolute; height: 0%; width: 100%; padding-bottom: 100%; background-color: var(–uib-color); border-radius: 50%; }

.three-body__dot:nth-child(1) { bottom: 5%; left: 0; transform: rotate(60deg); transform-origin: 50% 85%; }

.three-body__dot:nth-child(1)::after { bottom: 0; left: 0; animation: wobble1 var(–uib-speed) infinite ease-in-out; animation-delay: calc(var(–uib-speed) * -0.3); }

.three-body__dot:nth-child(2) { bottom: 5%; right: 0; transform: rotate(-60deg); transform-origin: 50% 85%; }

.three-body__dot:nth-child(2)::after { bottom: 0; left: 0; animation: wobble1 var(–uib-speed) infinite calc(var(–uib-speed) * -0.15) ease-in-out; }

.three-body__dot:nth-child(3) { bottom: -5%; left: 0; transform: translateX(116.666%); }

.three-body__dot:nth-child(3)::after { top: 0; left: 0; animation: wobble2 var(–uib-speed) infinite ease-in-out; }

@keyframes spin78236 { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

@keyframes wobble1 { 0%, 100% { transform: translateY(0%) scale(1); opacity: 1; } 50% { transform: translateY(-66%) scale(0.65); opacity: 0.8; } }

@keyframes wobble2 { 0%, 100% { transform: translateY(0%) scale(1); opacity: 1; } 50% { transform: translateY(66%) scale(0.65); opacity: 0.8; } }

For now i will use the file watcher from webstorm to add the @reference when needed

/**
 * @file WebStorm File Watcher Configuration for `add-tailwind-reference.js`
 *
 * This JSDoc comment provides instructions for setting up a WebStorm File Watcher
 * to automatically manage `@reference` lines in SCSS files based on the presence of `@apply`.
 *
 * @example
 * // 1. Open WebStorm Settings:
 * //    File > Settings... (or WebStorm > Preferences... on macOS)
 * //    Navigate to Tools > File Watchers.
 *
 * // 2. Add a New File Watcher:
 * //    Click the + (Add) button.
 * //    Select Custom.
 *
 * // 3. Configure the File Watcher:
 * //    Name: add-tailwind-reference (or any descriptive name).
 * //    Files to Watch:
 * //      File type: SCSS style sheet.
 * //      Scope: Project Files.
 * //      Track only root files: (Leave unchecked unless needed).
 * //    Tool to Run on Changes:
 * //      Program: C:\Program Files\nodejs\node (Adjust if your Node.js path is different).
 * //      Arguments: add-tailwind-reference.js $FilePath$
 * //        - `add-tailwind-reference.js`: The name of your script.
 * //        - `$FilePath$`: WebStorm macro for the changed file's path.
 * //      Output paths to refresh: (Leave blank or add specific paths).
 * //      Working directory: $ContentRoot$.
 * //      Environment variables: (Leave as is).
 * //    Advanced Options:
 * //      Auto-save edited files to trigger the watcher: (Check for immediate execution on save).
 * //      Trigger the watcher on external changes: (Check to trigger on external modifications).
 * //      Trigger the watcher regardless of syntax errors: (Check with caution).
 * //      Create output file from stdout: (Leave unchecked).
 * //    Show console: On error.
 * //    Output filters: (Leave blank or add regex filters).
 *
 * // 4. Click OK to save the configuration.
 *
 * @remarks
 * - Ensure the Node.js path is correct.
 * - Place `add-tailwind-reference.js` in the project root or a discoverable location.
 * - Verify file permissions for Node.js.
 * - Use `console.log()` in the script for debugging.
 *
 * @see {@link https://www.jetbrains.com/help/webstorm/file-watchers.html WebStorm File Watchers Documentation}
 * @see {@link https://nodejs.org/ Node.js Official Website}
 *
 * @param {string} $FilePath$ - The absolute path of the SCSS file that triggered the watcher. (WebStorm macro)
 * @param {string} $ContentRoot$ - The root directory of the project. (WebStorm macro)
 *
 * @example
 * // Example command line arguments:
 * // add-tailwind-reference.js /path/to/your/file.scss
 *
 * @example
 * // Example script usage:
 * // node add-tailwind-reference.js path/to/your/file.scss
 */
const fs = require('fs');
const path = require('path');


function processScssFile(filePath, cssFilePath) {
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file ${filePath}: ${err}`);
      return;
    }

    const relativePath = path.relative(path.dirname(filePath), cssFilePath).replace(/\\/g, '/');
    const referenceLine = `@reference "${relativePath}";\n`;
    const applyRegex = /@apply\b/;

    if (applyRegex.test(data)) {
      // Check for the reference line *before* adding it
      if (!data.includes(referenceLine.trim())) { // Use includes for a more robust check.
        const updatedData = referenceLine + data;
        fs.writeFile(filePath, updatedData, 'utf8', (writeErr) => {
          if (writeErr) {
            console.error(`Error writing to file ${filePath}: ${writeErr}`);
          } else {
            console.log(`Updated ${filePath} with reference: ${referenceLine.trim()}`);
          }
        });
      } else {
        console.log(`${filePath} already contains the reference.`);
      }
    } else {
      // Remove reference if @apply is not found
      const trimmedData = data.replace(/^[\s\n]+/, ''); // Remove leading whitespace and newlines

      if (trimmedData.startsWith(referenceLine.trim())) {
        const updatedData = data.slice(referenceLine.length);
        fs.writeFile(filePath, updatedData, 'utf8', (writeErr) => {
          if (writeErr) {
            console.error(`Error writing to file ${filePath}: ${writeErr}`);
          } else {
            console.log(`Removed reference from ${filePath}.`);
          }
        });
      } else {
        console.log(`${filePath} does not contain the reference.`);
      }
    }
  });
}

processScssFile(process.argv[2], 'path-to-your-theme/theme.css');

Hello, I have previously upgraded the tailwind v4 of a project.

You can refer to this repo nextjs-nextra-starter and Commits

Image

很酷

Image

You can try starting the path with a slash:

@reference "/home/users/project/src/app.css";

So I recently started to migrate TailwindCSS v3 to v4. In v3, there was detailed documentation regarding different paddings. Also, there is the possibility to use py-1 and px-1. However, after the migration, I get Cannot apply unknown utility class: py-1 Cannot apply unknown utility class: px-1 I am not able to find something helpful in the documentation, is there something, that is not done properly? This is an example where it does not work anymore: <div class="py-1 select-none">

If you’re using @apply anywhere, I’d look at those first! My issue was that I was not importing tailwind into my <style> blocks in Vue SFC’s. But I ended up refactoring so that I was not using any tailwindcss classes in <style> tags.

Yikes, that’s painful to hear. I would look at getting reference to work, using v3 config files (easier globals) or moving style to a component style sheet.

just out of curiosity, why was v4 built this way that the global @apply doesn’t work anymore? i mean there has to be some reason for it I don’t understand yet

See https://github.com/tailwindlabs/tailwindcss/issues/15778#issuecomment-2616412050

just out of curiosity, why was v4 built this way that the global @apply doesn’t work anymore? i mean there has to be some reason for it I don’t understand yet

Sorry for hijacking a closed issue, but it’s normal that this issue appears with custom color classes? Given now that the V4 config file is not global. Is there any workaround around this?

@bugproof If you’re using Vite you can use resolve aliases for CSS files.

@apply in v4 is no longer “global” as it was in v3. Furthermore, v4 does not read tailwind.config.js by default whereas v3 does.

Thanks for your response. I didn’t understand that @reference is an obligation. This is certaining a breaking change, and not documented at all.

You may need to use @reference in your src/scss/components/_buttons.scss.

It could also be that Sass evaluates the @imports before Tailwind which could cause problems. Consider seeing if there is a way to exclude the @import processing from Sass.

Otherwise, please consider providing a more all-encompassing example - like a remotely-hosted git repository. This is so I don’t have to figure out which packages I need to install and other such things that take time to setup but not condusive to the problem.

You may not want to @import the main stylesheet again, as that will duplicate the Tailwind-generated CSS in the other file. You would use @reference instead.

Oh! I think I should have understood. Thank you!