Styling: CSS Modules & Tailwind

Styling: CSS Modules & Tailwind in React: --- A sprawling warehouse is used by many teams at once, and every team stores parts in bins they label by hand.


The Analogy: A Shared Warehouse's Bin-Labeling System

A sprawling warehouse is used by many teams at once, and every team stores parts in bins they label by hand. Early on this is fine: shipping writes "bolts" on a bin, assembly writes "red" on another. But as the floor fills, two teams inevitably chalk the same short label on different bins -- shipping's "bolts" and fabrication's "bolts" -- and a picker sent for "bolts" grabs whichever bin they reach first. The labels live in one flat, shared namespace, so collisions are not a risk but a certainty, and the only tie-breaker is who happened to relabel last.

One fix keeps the hand-written labels but runs every bin past a stamping machine on its way to the floor. The machine prints the team's department code and a unique serial onto the label, so "bolts" from shipping becomes "SHIP-bolts-7F3A" and "bolts" from fabrication becomes "FAB-bolts-9C21". The teams still think and write in short names; the machine guarantees that no two finished labels can ever match. Pickers read the stamped label, so they can never confuse the two bins again. This is scoping by transformation: uniqueness is enforced by the system, not by everyone remembering to be careful.

A different fix abolishes custom labels almost entirely. The warehouse issues a fixed catalog of standard, pre-made totes -- "small-blue-tote", "6-inch-shelf", "half-width-divider" -- and a workstation is assembled by grabbing a handful of these standard parts rather than naming a bespoke bin. Two benches built from the same standard totes look and behave identically, and because nobody invents a new name, there is nothing to collide. When two totes claim the same slot on a bench, the one placed later simply sits on top; stacking order, not the order you happened to list them, decides what is visible.

Both systems have a soft underbelly, and it is the same one: escapes. The stamping machine only protects labels that pass through it; a label someone scrawls by hand and slaps straight onto the global rack skips the serial and can collide with anything. The standard-catalog approach leaves the bench tag reading as a long unreadable strip of tote codes, and offers no standard part for a genuinely one-off shape, tempting a worker to smuggle in a custom bin that quietly brings the old collision problem back. Choosing a system and then routinely escaping it is worse than committing to either one.


Syntax or Core Structure

CSS Modules and Tailwind are two answers to one question: how do a component's styles reach it without leaking into the rest of the app. CSS Modules imports a styles object whose keys are your local class names and hands back generated, unique class strings. Tailwind skips custom names entirely and writes fixed utility classes straight into className.

// CSS Modules: import the generated names, reference them by key.
import styles from "./Button.module.css";
function Button() {
  return <button className={styles.error}>Retry</button>;
}

// Tailwind: compose fixed utility classes inline; no custom names.
function Badge() {
  return <span className="px-2 py-1 text-red-600 bg-red-100">Error</span>;
}

The classes Tailwind emits are exactly what you type. The classes CSS Modules emits are generated: your local error becomes something globally unique. That transform is a pure function of the file and the local name, so we can model it directly and trace it by hand.

// CSS Modules turns a local class name into a globally-unique one.
// The result is a pure function of the component file and local name.
function scopeName(componentFile, localName, hash) {
  return componentFile + "_" + localName + "__" + hash;
}

console.log(scopeName("Button", "error", "a1b2c"));
console.log(scopeName("Alert", "error", "9x8y7"));

Output:

Button_error__a1b2c
Alert_error__9x8y7

Two components both use the local name error, yet the transform yields two distinct global classes, so they can never collide. The mapping is deterministic: the same file and local name always produce the same scoped class.


Technical Depth: How Each System Prevents (and Reintroduces) Collisions

Two "error" classes, one global namespace

The whole point of scoping is visible when two components pick the same local name. Without scoping both collapse to .error and the last stylesheet loaded wins for everyone; with scoping they stay distinct.

function applyStyles(useModules, files) {
  return files.map(function (f) {
    var emitted = useModules
      ? f.file + "_" + f.local + "__" + f.hash
      : f.local;
    return f.file + "." + f.local + " -> ." + emitted;
  });
}
var files = [
  { file: "Button", local: "error", hash: "a1b2c" },
  { file: "Alert", local: "error", hash: "9x8y7" }
];
console.log("global CSS:");
console.log(applyStyles(false, files).join("
"));
console.log("CSS Modules:");
console.log(applyStyles(true, files).join("
"));

Output:

global CSS:
Button.error -> .error
Alert.error -> .error
CSS Modules:
Button.error -> .Button_error__a1b2c
Alert.error -> .Alert_error__9x8y7

Under global CSS both authored classes emit the same .error, a genuine collision. Under CSS Modules they emit different strings, so the styles stay isolated no matter how many components reuse the word error.

ApproachAuthor writesEmitted classCollision risk
Global CSS.error.errorhigh (shared namespace)
CSS Modules.error.Button_error__a1b2cnone (auto-scoped)
Tailwindtext-red-600text-red-600none (fixed vocabulary)

A utility conflict resolves by stylesheet order, not string order

A common Tailwind trap: writing p-2 p-6 and assuming the last one in the string wins. Both set padding, and the winner is whichever rule appears later in the generated stylesheet -- the order inside the className string is irrelevant.

// Two utilities set the same property. The one defined LATER in the
// stylesheet wins -- not the one written last in the class string.
var sheetOrder = { "p-2": 1, "p-6": 2 };  // p-6 is defined later in the CSS
function resolvePadding(classString) {
  var setters = classString.split(" ").filter(function (c) {
    return sheetOrder[c] !== undefined;
  });
  setters.sort(function (a, b) { return sheetOrder[a] - sheetOrder[b]; });
  return setters[setters.length - 1];
}
console.log(resolvePadding("p-2 p-6"));
console.log(resolvePadding("p-6 p-2"));

Output:

p-6
p-6

Both orderings yield p-6 because p-6 is defined later in the sheet. You cannot override a utility just by listing another one after it; to change the value you remove the loser or merge the pair with a tool like tailwind-merge.

Scoping only protects what goes through the compiler

CSS Modules provides a :global escape hatch. Anything inside it skips the transform and re-enters the shared namespace, exactly the risk scoping was meant to remove.

function emit(local, isGlobal, file, hash) {
  return isGlobal ? "." + local : "." + file + "_" + local + "__" + hash;
}
console.log(emit("error", false, "Button", "a1b2c"));  // scoped
console.log(emit("error", true, "Button", "a1b2c"));    // :global escape

Output:

.Button_error__a1b2c
.error

The scoped call stays unique; the :global call emits a bare .error that can collide with any other global .error in the app. Escapes are sometimes necessary, but each one is a hole in the guarantee.

Composing conditional classes without string-concatenation bugs

Real components rarely apply a fixed class list; they toggle classes on state. Hand-building that with + and template strings leaks stray spaces and false tokens into the markup. The clsx/classnames pattern is a pure function: keep truthy string tokens, and for object arguments keep each key whose value is truthy. It works the same whether the tokens are scoped module classes or Tailwind utilities.

// Keep truthy string tokens; for objects keep keys with a truthy value.
function cx() {
  var out = [];
  for (var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if (!arg) continue;
    if (typeof arg === "string") {
      out.push(arg);
    } else {
      Object.keys(arg).forEach(function (name) {
        if (arg[name]) out.push(name);
      });
    }
  }
  return out.join(" ");
}
console.log(cx("btn", false, { active: true, disabled: false }));
console.log(cx("btn", null, { active: false, loading: true }));

Output:

btn active
btn loading

Falsy arguments are dropped, so a disabled branch never emits a stray false or a doubled space, and the result is a single clean class string. Like assembling a bench from standard totes, you list the parts you want and skip the ones you do not; the composer guarantees a tidy tag.


Real World Example: A Reusable Button That Accepts a className Override

A theming team ships a Button styled with CSS Modules, and to stay flexible they let callers pass a className that is concatenated onto the component's own class. A product team passes caller-danger to turn a button red. It works on their machine, ships, and then breaks on a lazily-loaded route. Both classes set color with equal specificity, so the winner is decided entirely by which rule sits later in the final stylesheet -- and that order depends on module load order, which the component does not control.

// Button applies its own class plus a caller-provided override.
// Both set color with EQUAL specificity, so the later rule in the
// stylesheet wins -- and that depends on load order, not string order.
function winner(applied, sheetOrder) {
  var setters = applied.filter(function (c) {
    return sheetOrder[c] !== undefined;
  });
  setters.sort(function (a, b) { return sheetOrder[a] - sheetOrder[b]; });
  return setters[setters.length - 1];
}
var applied = ["Button_button__h1", "caller-danger"];
// Case A: component module loaded LAST (lazy route / CSS-in-JS injection)
console.log("module last: ", winner(applied, { "caller-danger": 1, "Button_button__h1": 2 }));
// Case B: component module loaded FIRST (plain top-of-file import)
console.log("module first:", winner(applied, { "Button_button__h1": 1, "caller-danger": 2 }));

Output:

module last:  Button_button__h1
module first: caller-danger

The two runs use the same applied classes in the same order, yet the winner flips. In Case B the override lands as intended; in Case A the component's own class loads later and silently beats the override, so the button stays its default color and no error is ever raised. This is the exact shape of the "why won't my override apply" bug that appears only after a bundler splits chunks or a route is lazy-loaded.

The Button merges className by plain concatenation -- ${styles.button} ${className} -- and assumes the caller's class wins. Because both classes have equal specificity, the real tie-breaker is stylesheet source order, which the component cannot guarantee. The honest fixes are to make the override explicit and higher-specificity (a documented data-attribute selector, or && in a CSS-in-JS API), to dedupe conflicting utilities deterministically with tailwind-merge, or to expose named variants instead of a raw className passthrough. And the scoped name Button_button__h1 is a build artifact whose hash changes every build, so it must never be hard-coded anywhere -- always reach it through the imported styles object.


Common Mistakes

  1. Leaning on global class names in a large app. Short shared names like .error or .active collide across components, and you end up debugging why one component restyled another.
  1. Assuming the last class in a Tailwind string wins. Order inside className does not decide conflicts; the order rules appear in the generated stylesheet does. p-2 p-6 and p-6 p-2 resolve identically.
  1. Hard-coding a generated CSS Modules class name. Strings like Button_button__h1 are build artifacts whose hash changes every build; reference them only through the imported styles object.
  1. Overusing :global in CSS Modules. Every :global escape re-enters the shared namespace that scoping exists to avoid, quietly reopening the collision door.
  1. Reaching for !important to win a specificity fight. It does not end the war, it escalates it; the next author just adds another !important. Restructure the selectors instead.
  1. Passing a raw className override and assuming it wins. If it has the same specificity as the component's own class, stylesheet load order decides -- so the override works in one build and fails in another.
  1. Duplicating conflicting Tailwind utilities instead of merging them. Shipping p-2 p-6 leaves dead classes in the markup; tailwind-merge collapses them to the intended one.
  1. Mixing several styling systems at once. Global CSS plus Modules plus inline styles plus utilities makes the effective style of an element genuinely hard to predict or debug.
  1. Building Tailwind class names dynamically. A string like text-${color} is invisible to the compiler at build time, so the utility gets purged and the style silently disappears in production.

Best Practices

  • Pick one primary styling strategy per project and treat every escape from it as a deliberate, documented exception.
  • Let CSS Modules or Tailwind own scoping for you instead of hand-namespacing global class names with prefixes.
  • Reference generated module classes only through the imported styles object, never by their literal emitted string.
  • Merge conflicting Tailwind utilities with tailwind-merge (or clsx plus a merge step) rather than shipping duplicates.
  • Expose named variants or props for the override points you actually support, in preference to a raw className passthrough.
  • Reserve !important and :global for rare, commented cases where no cleaner option exists.
  • Write full, static utility strings so Tailwind's compiler can see and keep them; never assemble class names from runtime values.
  • Keep specificity flat and consistent so that overrides behave the same way across dev builds and split production bundles.

Practice Exercises

  1. Run scopeName for ("Button", "error", ...) and ("Alert", "error", ...). Explain in one sentence why two components using the local name error never collide under CSS Modules.
  1. Run resolvePadding("p-2 p-6") and resolvePadding("p-6 p-2"). Explain why both return p-6 and what that implies about overriding a Tailwind utility by appending another one.
  1. Run the winner model once with the component module ordered first and once ordered last. Explain why the identical className override can apply in one build and silently fail in another, and name one fix.
  1. Take a component that uses two colliding global classes. Convert it to CSS Modules, then separately restyle it with Tailwind utilities, and note which specific naming problem each approach removes.