All articles
Tailwind CSSCSSNext.jsDebugging

Tailwind Classes Not Applying? Every Cause and the Fix

Tailwind class in the markup but no style on screen? Learn to tell a class that was never generated from one that loses, then fix each cause.

Tushar Pachouri14 min read

A Tailwind class that does nothing gives you no error, no warning and no failed build. The class sits right there on the element in DevTools and the element ignores it. I hit this on this very site when the project cards went transparent in a production build, so this article starts with that case and then covers every other way a Tailwind class can silently fail, with broken and fixed code for each.

TL;DR

  • Tailwind only generates CSS for class names it finds as complete strings in the files it scans. A class that lives in a file outside your content globs (v3) or outside source detection (v4) does not exist.
  • Never build class names from fragments like bg-${color}-500. Map values to full class strings, or safelist them.
  • If the rule exists but loses, the cause is stylesheet order or specificity, not the order of classes in your attribute. Use tailwind-merge in components that accept className.
  • Debug by searching the built CSS. No rule means a scanning problem, a struck-through rule means a cascade problem, and no utilities at all means the PostCSS pipeline is not running.

The case: transparent project cards

The featured projects section on this site renders each project as a rounded card with its own pastel background and coloured shadow. The project array used to live inside src/components/sections/FeaturedProjects.tsx. During an SEO pass I moved it into src/lib/projects.ts so the structured data for search engines could share it. Each project carries its colours as Tailwind class strings:

TypeScript
export const projects = [
  {
    id: 1,
    title: "PortfolioForge",
    color: "bg-[#e0efff]",
    shadow: "shadow-blue-200/50",
  },
  {
    id: 2,
    title: "bnao.ai",
    color: "bg-[#fff8df]",
    shadow: "shadow-yellow-200/40",
  },
];

The component interpolates those strings into the card's className. A simplified version:

TSX
import { projects } from "@/lib/projects";

export function ProjectCards() {
  return (
    <div className="grid gap-6">
      {projects.map((project) => (
        <article
          key={project.id}
          className={`rounded-[40px] p-8 shadow-2xl ${project.color} ${project.shadow}`}
        >
          <h3 className="text-2xl font-semibold">{project.title}</h3>
        </article>
      ))}
    </div>
  );
}

Nothing else changed and TypeScript was happy. In the production build, though, every card rendered transparent: titles and preview images floated on the page background with no card colour and no coloured shadow.

Why it happened

Tailwind v3 never looks at your running app. It reads the files matched by the content globs in tailwind.config, extracts every token that could be a class name, and generates CSS only for those. This site's config listed three folders: src/pages, src/components and src/app.

The arbitrary-value classes like bg-[#e0efff] now existed only in src/lib/projects.ts, which none of those globs matched. As far as Tailwind could tell, nobody used them, so the production stylesheet had no rule for them. The shadow classes such as shadow-blue-200/50 vanished for the same reason.

The data file sat outside every content glob, so its classes were never generated.

The fix

One glob:

Diff
   content: [
     "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
     "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
     "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
+    // Data files that carry class names (e.g. project card colours in src/lib/projects.ts)
+    "./src/lib/**/*.{js,ts,jsx,tsx}",
   ],

To confirm that was the whole story, I rebuilt the stylesheet with the project's own Tailwind CLI against both versions of the config. With the old globs, the output had no rule for any card background or shadow colour; with src/lib added, every one was there.

Note: A stale dev stylesheet can hide this kind of bug. Tailwind v3's watch mode is built to add rules quickly as it sees new classes, and as far as I know it does not prune rules mid-session, so classes generated while the data still lived in the component can linger until you restart the dev server. A fresh production build is the honest test.

How the scanner sees your code

The scanner treats your files as plain text. It does not run JavaScript, follow imports or evaluate template literals; it splits the text into tokens and keeps those that match a utility it knows. While checking the arbitrary-value example later in this article, my test file had the word "fixed" as text inside a div, and the generated CSS gained a .fixed { position: fixed } rule. The reverse also holds: a class that never appears as a complete string in a scanned file is never generated.

That gives three kinds of failure, and telling them apart is most of the work:

What you seeWhat it meansWhere to look
Class on the element, no matching rule anywhereNever generatedContent globs, source detection, dynamic names
Rule exists but is struck throughGenerated, but losingClass order, specificity, third-party CSS
No Tailwind utility works at allPipeline not runningPostCSS config, CSS import

Find out which failure you have

Search the built CSS

Build for production, then search the emitted stylesheets. Tailwind escapes special characters in selectors, so bg-[#e0efff] becomes .bg-\[\#e0efff\] in the CSS. Rather than fight the escaping, search for a distinctive part of the value:

Terminal
npm run build
grep -o '[^}]*e0efff[^}]*}' .next/static/css/*.css

On this site, after the fix, that prints the rule:

Text
.next/static/css/3df2d7e0fdeb34ca.css:.bg-\[\#e0efff\]{--tw-bg-opacity:1;background-color:rgb(224 239 255/var(--tw-bg-opacity,1))}

Your file hash will differ. If the command prints nothing, the rule was never generated. In PowerShell, this lists the files that contain the value and prints nothing if none do:

PowerShell
npm run build
Select-String -Path .next\static\css\*.css -Pattern "e0efff" -SimpleMatch -List | Select-Object -ExpandProperty Filename

If you changed distDir in next.config, search there instead. This site keeps dev output in a separate .next-dev folder, so .next only ever holds production builds.

Check the element in DevTools

Inspect the element and type the class name into the filter box in the Styles pane. If no rule appears, it was never generated. If the rule appears with its declarations struck through, something else wins; the winning rule is listed above it, and the Computed tab shows the final value and where it came from.

For a quick answer, paste this into the console. It walks every same-origin stylesheet, including rules nested inside @media and @layer blocks, which matters for v4 where all utilities sit inside a layer:

JavaScript
function findRules(className) {
  const selector = "." + CSS.escape(className);
  const found = [];
  const walk = (rules) => {
    for (const rule of rules) {
      if (rule.selectorText && rule.selectorText.includes(selector)) {
        found.push(rule.cssText);
      }
      if (rule.cssRules) walk(rule.cssRules);
    }
  };
  for (const sheet of document.styleSheets) {
    try {
      walk(sheet.cssRules);
    } catch {
      // Cross-origin stylesheets throw when you read cssRules
    }
  }
  return found.length ? found : `No CSS rule matches .${className}`;
}

findRules("bg-[#e0efff]");

Class names built from pieces

This is the most common cause by far. The scanner sees bg-${color}-500 as text, and no complete class name appears in it:

TSX
type BadgeColor = "red" | "green" | "blue";

export function Badge({ color, label }: { color: BadgeColor; label: string }) {
  return <span className={`bg-${color}-500 text-white`}>{label}</span>;
}

I ran this file through the Tailwind CLI: the output contained .text-white and nothing else. The fix is to write every class in full and choose between them at runtime:

TSX
const badgeColors = {
  red: "bg-red-500",
  green: "bg-green-500",
  blue: "bg-blue-500",
} as const;

type BadgeColor = keyof typeof badgeColors;

export function Badge({ color, label }: { color: BadgeColor; label: string }) {
  return <span className={`${badgeColors[color]} text-white`}>{label}</span>;
}

Now all three background rules are generated, <Badge color="green" label="Live" /> renders <span class="bg-green-500 text-white">Live</span>, and TypeScript checks the allowed colours.

When you genuinely cannot list the classes in source, v3 lets you safelist them. Patterns are regular expressions matched against class names Tailwind knows how to generate:

TypeScript
import type { Config } from "tailwindcss";

const config: Config = {
  content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
  safelist: [
    "ring-2",
    { pattern: /^bg-(red|green|blue)-500$/ },
  ],
};

export default config;

Keep safelists narrow, since every entry ships whether you use it or not. If you need variants, a pattern entry also accepts a variants array such as ["hover"].

Markdown, CMS and node_modules

The same thing happens with any class names that live outside the scanned folders.

  • Markdown and MDX. If your posts contain raw HTML or JSX with Tailwind classes, the content folder has to be scanned too.
  • Component packages. A UI library that ships Tailwind class names in its compiled JavaScript needs its dist folder scanned. Point at that package specifically; a broad pattern over all of node_modules is very slow, and recent v3 releases warn when a pattern looks like it matches all of it.
TypeScript
import type { Config } from "tailwindcss";

const config: Config = {
  content: [
    "./src/**/*.{js,ts,jsx,tsx,mdx}",
    "./content/**/*.{md,mdx}",
    "./node_modules/@acme/ui/dist/**/*.{js,mjs}",
  ],
};

export default config;
  • A CMS or database. Class names stored in a CMS are not in any file, so no glob can find them. Store a meaning instead (tone: "warning") and map it to full classes in code:
TypeScript
const calloutTone = {
  info: "border-sky-300 bg-sky-50 text-sky-900",
  warning: "border-amber-300 bg-amber-50 text-amber-900",
} as const;

type CalloutTone = keyof typeof calloutTone;

export function calloutClasses(tone: string): string {
  return Object.hasOwn(calloutTone, tone)
    ? calloutTone[tone as CalloutTone]
    : calloutTone.info;
}

An unknown tone falls back to info instead of producing a class that was never generated.

Tailwind v4 looks in different places

Tailwind v4 changed configuration and scanning, so v3 advice can mislead you. Details have shifted across v4 releases, so check the docs for your version, but broadly:

  • Configuration lives in CSS. You load Tailwind with @import "tailwindcss"; instead of the three @tailwind directives, and a JavaScript config file is only used if you point at it with @config.
  • There is no content array. Tailwind detects sources automatically, skipping files listed in .gitignore, node_modules, binary files and CSS files.
  • Anything detection skips can be added with @source, using a path relative to the stylesheet.
CSS
@import "tailwindcss";

/* Paths are relative to this file, src/app/globals.css */
@source "../../content";
@source "../../node_modules/@acme/ui/dist";

The .gitignore rule is the v4 version of my transparent cards. If a script generates data files into an ignored folder, their classes are never generated until you add an @source for it. Recent v4 releases also offer @source inline(...) as a replacement for the safelist; check that your version supports it before relying on it.

The later class does not win

A component accepts a className and appends it, expecting the caller's classes to override its defaults:

TSX
import type { ReactNode } from "react";

export function Button({ className = "", children }: { className?: string; children: ReactNode }) {
  return (
    <button className={`rounded-lg px-4 py-2 bg-gray-900 text-white ${className}`}>
      {children}
    </button>
  );
}

Then <Button className="bg-blue-600 px-6">Save</Button> stays gray. Both rules have the same specificity, so the one later in the stylesheet wins, and Tailwind decides that order, not your attribute. In Tailwind 3.4, .bg-blue-600 is emitted before .bg-gray-900, so gray wins, while px-6 happens to beat px-4, which makes the bug look random.

CLASS ATTRIBUTE STYLESHEET ORDER, 3.4 rounded-lg px-4 py-2 bg-gray-900 text-white bg-blue-600 px-6 added by the caller Attribute order does not decide. Equal specificity: the later CSS rule wins. .bg-blue-600 .bg-gray-900 .px-4 .px-6 ... earlier, loses later, wins earlier, loses later, wins background: gray-900 wins, stays gray padding: px-6 wins, looks right
Stylesheet order, not attribute order, decides which of two equal utilities wins.

The fix is to drop the conflicting class before it reaches the DOM. tailwind-merge knows which utilities conflict and keeps the last one:

TypeScript
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

const base = "rounded-lg px-4 py-2 bg-gray-900 text-white";

console.log(clsx(base, "bg-blue-600 px-6"));
console.log(cn(base, "bg-blue-600 px-6"));
console.log(cn("p-4", "px-2"));
console.log(cn("px-2", "p-4"));

Running it with npx tsx prints:

Text
rounded-lg px-4 py-2 bg-gray-900 text-white bg-blue-600 px-6
rounded-lg py-2 text-white bg-blue-600 px-6
p-4 px-2
p-4

It even understands shorthands: px-2 after p-4 is a refinement and both are kept, while p-4 after px-2 replaces it. Use cn(base, className) in every component that accepts a className.

Tip: tailwind-merge major versions track Tailwind major versions. At the time of writing, v2 targets Tailwind v3 and v3 targets Tailwind v4. Check its README when you upgrade.

Specificity and Preflight

Tailwind utilities are single-class selectors. In v3, and for unlayered CSS in v4, any rule with higher specificity beats them, wherever it sits in the stylesheet. Third-party widget CSS is the usual source:

CSS
/* vendor.css shipped with a chat widget */
.chat-widget button {
  background-color: #ffffff;
}
HTML
<div class="chat-widget">
  <button class="bg-blue-600 text-white">Send</button>
</div>

.chat-widget button has a class and an element, so it beats .bg-blue-600 and the button stays white. You can raise the utility with the important modifier (next section), or remove the vendor rule if the library lets you.

Tailwind v4 emits native CSS cascade layers, and the cascade checks layer order before specificity. Unlayered normal declarations beat layered ones, so vendor CSS or plain CSS in globals.css can override utilities even with a weak selector like button. Rules in @layer base or @layer components lose to utilities whatever their selector, so keep custom CSS in those layers.

TAILWIND V4 CASCADE, STRONGEST FIRST beats the layers below Unlayered CSS @layer utilities @layer components @layer base vendor CSS, plain rules in globals.css bg-blue-600, px-6 and the rest your custom component CSS resets and element defaults beats utilities, even as plain button your Tailwind classes loses to utilities, any selector loses to utilities, any selector
In v4 layer order is checked before specificity, so unlayered CSS beats utilities.

Preflight, Tailwind's base reset, causes the opposite confusion. It strips default margins, heading sizes and list styles, so rendered Markdown looks bare (that is what the typography plugin's prose class is for), and it can restyle third-party components that expect browser defaults. In v3 you can turn it off:

TypeScript
import type { Config } from "tailwindcss";

const config: Config = {
  content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
  corePlugins: {
    preflight: false,
  },
};

export default config;

The important modifier

In v3 you mark a single utility as important with a leading !. For !bg-blue-600, Tailwind 3.4 generates:

CSS
.\!bg-blue-600 {
  --tw-bg-opacity: 1 !important;
  background-color: rgb(37 99 235 / var(--tw-bg-opacity, 1)) !important
}

The ! goes after any variants: in 3.4, hover:!underline works, while !hover:underline generated nothing when I tried it. In v4 the documented form puts the ! at the end, as in bg-blue-600!; the old prefix is still accepted as far as I know, but check the upgrade guide for your version. v3 also has a global important option, either true or a selector such as "#app". Use both sparingly.

Dark mode strategy mismatch

In v3 the default dark mode strategy is media: dark: utilities follow the operating system setting. If a theme toggle adds a dark class to <html> but the config still uses media, your toggle does nothing. With the default config, Tailwind 3.4 generates:

CSS
@media (prefers-color-scheme: dark) {
  .dark\:bg-gray-900 {
    --tw-bg-opacity: 1;
    background-color: rgb(17 24 39 / var(--tw-bg-opacity, 1))
  }
}

This site uses next-themes with attribute="class", so the config sets the class strategy:

Diff
 const config: Config = {
+  darkMode: "class",
   content: ["./src/**/*.{js,ts,jsx,tsx,mdx}"],
 };

With that, the same utility becomes .dark\:bg-gray-900:is(.dark *). Note the descendant selector: the element carrying the dark class does not match its own dark: utilities. Recent 3.4 releases also accept "selector", which generates :where(.dark, .dark *) and matches both.

In v4 the default is also the media query, and you switch to a class by overriding the variant in CSS:

CSS
@import "tailwindcss";

@custom-variant dark (&:where(.dark, .dark *));

Spaces in arbitrary values

A class attribute is split on whitespace, so an arbitrary value with a space becomes two meaningless tokens:

TSX
export function Layout() {
  return (
    <div>
      <div className="grid grid-cols-[200px minmax(0,1fr)]">broken</div>
      <div className="grid grid-cols-[200px_minmax(0,1fr)]">fixed</div>
    </div>
  );
}

Only the underscore version generates a rule, and Tailwind converts the underscore back to a space:

CSS
.grid-cols-\[200px_minmax\(0\2c 1fr\)\] {
  grid-template-columns: 200px minmax(0,1fr)
}

If you need a literal underscore inside an arbitrary value, escape it with a backslash.

The pipeline is not running

If no utility works anywhere, Tailwind is not processing your CSS at all. For v3 in Next.js, you need a PostCSS config in the project root. This is the one this site uses, as postcss.config.mjs:

JavaScript
/** @type {import('postcss-load-config').Config} */
const config = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

export default config;

In Next.js 14, which this site uses, the lookup searches upward from the project root for names like postcss.config.js, .mjs or .cjs (or a postcss key in package.json). A config with a typo in its name, or one placed inside src, is not found, and Next falls back to its default PostCSS setup, which does not include Tailwind. In v4 the PostCSS plugin moved to its own package:

JavaScript
const config = {
  plugins: {
    "@tailwindcss/postcss": {},
  },
};

export default config;

Finally, the stylesheet has to be imported. In the App Router that means import "./globals.css"; in src/app/layout.tsx. If the served CSS still contains raw @tailwind or @import "tailwindcss" lines, or never loads in the Network tab, start here.

Checklist

  1. Search the built CSS for the class or its value. Decide whether it is missing, losing or the whole pipeline is down.
  2. Missing? Check that the file holding the class is covered by content (v3) or detection and @source (v4), including data files, Markdown, packages and gitignored folders.
  3. Built from pieces? Replace template-literal class names with a map of full strings, or a narrow safelist.
  4. Struck through? Check for a same-property utility that comes later in the stylesheet and use tailwind-merge, then look for higher-specificity or unlayered third-party CSS.
  5. Dark variants ignored? Make the dark mode strategy match how your toggle works.
  6. Arbitrary value ignored? Replace spaces with underscores.
  7. Nothing works? Check the PostCSS config name and location, the plugin package for your version, and the globals.css import.
  8. Confirm with a fresh production build, not a long-running dev server.

For the transparent cards on this site, step 2 was the whole story: one glob, and the colours came back.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch