Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 3

Comparing Styling Strategies: Modules, Utilities, Layers

Compare CSS Modules, utility-first CSS and cascade layers on what really matters at scale: name collisions, shipped bytes, specificity and how a team works.

Contentsand lesson path

What you will learn

  • Choose a scalable styling approach (CSS Modules, utility-first CSS such as Tailwind, or cascade layers) and justify its trade-offs in specificity control, shipped CSS and team workflow.

Prerequisites: CSS Cascade & Box Model

01. Why it matters

A styling strategy is a decision about how thirty developers share one stylesheet system. Chosen well, features ship without surprises: nobody's new rule breaks an unrelated page, the CSS you send to readers stays roughly proportional to what they see, and the design tokens from the previous lesson are the only source of raw values. Chosen badly, you get the classic symptoms: rules that fight each other, !important creeping in as a tiebreaker, and a stylesheet that only ever grows.

There is no single winner. CSS Modules, utility-first CSS and cascade layers solve different problems, and most real systems combine them. What this lesson gives you is the trade-offs, with evidence you can reproduce: what a bundler actually does to class names, and what a Tailwind build actually ships as an app grows. The cascade mechanics themselves — specificity, layer order, source order — you already know from the CSS foundations lesson; here they are material for an architecture decision.

02. CSS Modules: scoping by build step

CSS · src/components/badge.css (source)
.badge {
  padding: 2px 8px;
  border-radius: var(--radius-md);
}
.badge.is-urgent {
  background: var(--color-danger-soft);
}

A CSS Modules file is a normal stylesheet with one extra contract: every class is local to the file by default. The bundler rewrites the class names and hands the component a mapping, so the same local name in two files cannot collide. The script below scopes the file above with Lightning CSS (npm install -D [email protected]), one of the two CSS pipelines Vite can use (css.transformer: 'lightningcss'); the default PostCSS pipeline keeps the same contract with a different name generator.

JavaScript · modules-scope.mjs
// Scopes a stylesheet the way a CSS Modules bundler does, with Lightning CSS.
import { readFileSync } from 'node:fs';
import { transform } from 'lightningcss';

const filename = 'src/components/badge.css';
const { code, exports } = transform({
  filename,
  code: readFileSync(filename),
  cssModules: { pattern: '[name]__[local]___[hash]' },
});
console.log(code.toString().trim());
console.log('');
// Sort the keys: Lightning CSS may return them in a different order each run.
const mapping = Object.fromEntries(
  Object.entries(exports)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([local, e]) => [local, e.name]),
);
console.log(JSON.stringify(mapping, null, 2));
Expected output · node modules-scope.mjs
.badge__badge___63wzKG {
  border-radius: var(--radius-md);
  padding: 2px 8px;
}

.badge__badge___63wzKG.badge__is-urgent___63wzKG {
  background: var(--color-danger-soft);
}

{
  "badge": "badge__badge___63wzKG",
  "is-urgent": "badge__is-urgent___63wzKG"
}

The component imports the mapping and applies styles.badge, so the string in your markup is the generated name. Two teams, two .badge classes, two different generated names — the collision cannot happen. Notice what scoping does not do: specificity inside the module works exactly as before, !important still wins, and a rule that is never applied still ships, because the bundler cannot know whether the class name might be needed at run time.

03. Utility-first: classes as a generated API

Utility-first CSS (Tailwind is the widely used example) inverts the model: instead of naming rules per component, you compose single-purpose classes in the markup, and the framework generates the stylesheet from the classes your source actually uses. Tokens plug in through the theme configuration. With @theme inline, bg-brand compiles to background-color: var(--color-primary), the semantic token itself, so it still follows the dark theme, and the token file stays the only place a raw value lives.

CSS · app.css — the framework plus the project tokens
@import 'tailwindcss';

/* Theme names map to semantic tokens; never to their own name. */
@theme inline {
  --color-card: var(--color-surface);
  --color-body: var(--color-ink);
  --color-brand: var(--color-primary);
  --radius-card: var(--radius-md);
}
Illustrative output · @tailwindcss/cli 4.3.3 builds of two sample apps (not printed here)
small app (1 card, 1 button):   6222 bytes,  14 utility rules
same app, 30 more screens:    10002 bytes,  39 utility rules

Two rules keep that mapping honest. Point theme variables at semantic tokens: mapping --color-card to the palette value --gray-0 would compile bg-card to a fixed white that ignores the dark theme. And give every theme variable its own name. A custom property that refers to itself, such as --radius-md: var(--radius-md), is a dependency cycle and invalid at computed-value time; it only appears to work while an unlayered token declaration happens to override Tailwind's copy, and the radius drops to 0 the day the tokens move into a cascade layer ordered before Tailwind's theme layer. For the same reason, keep tokens.css unlayered: Tailwind's theme layer carries defaults with some of the same names, such as --radius-md.

In those two builds, thirty extra screens added under 4 KB, because each new class adds one small rule and reused classes cost nothing more. A hand-written component stylesheet would have grown by whole components instead. The flip side is where the cost moved: the markup now carries the styling. A className string of a dozen utilities is harder to review than a semantic name, repetition across similar buttons tempts copy-paste, and the standard remedy — extract a component — is a discipline, not a compiler rule.

04. Cascade layers: order as architecture

CSS · layer order declared once, at the top
@layer reset, base, components, utilities;

@layer reset {
  *, *::before, *::after { box-sizing: border-box; }
}
@layer base {
  h2 { margin-block: var(--space-4) var(--space-2); }
}
@layer components {
  .button { border-radius: var(--radius-md); }
}

Cascade layers are not a styling strategy on their own — they are a way to make groups of stylesheets agree on priority in advance. Layer order is compared before specificity: a rule in a later layer beats a more specific rule in an earlier one, and any unlayered rule beats all layered rules. That single ordering statement makes the normal cascade predictable: regular rules in a component layer beat regular rules in the reset layer regardless of selector specificity (though note that !important rules invert layer order), and component authors do not need artificially inflated selectors to establish default styles.

Layers also compose with the other two strategies. Utility frameworks ship their output in layers; a design system can put tokens in :root, components in a layer, and leave team-specific overrides unlayered on purpose, so local normal rules beat the layered ones without a specificity fight.

05. Choosing, and the remaining option

The trade-offs in one view
                CSS Modules      Utility-first      Cascade layers
Name clashes    prevented by     none (single-      unchanged; order
                build scoping    purpose classes)   agreed in advance
Shipped CSS     everything       only classes       unchanged
                in the module    found in source
Markup cost     semantic names   long class lists   semantic names
Specificity     as written       single-class       layers beat
                per file         rules by design    specificity
Team workflow   one file per     tokens in config   one order
                component        + components       statement

The option the table omits is CSS-in-JS, styles written in JavaScript and injected at run time. It buys colocated styling and dynamic values, and charges a run-time cost: injected styles must exist before first paint, code-splitting can delay them, and server rendering has to extract the styles carefully. The current direction in React ecosystems is zero-run-time variants that extract static CSS at build time, precisely to avoid those costs — which is worth knowing when a team proposes the run-time kind for a design system.

A practical default for a product team: tokens in :root (previous lesson), components as CSS Modules, a layer statement that fixes reset below components, and Tailwind where layout work is genuinely repetitive. Whatever you choose, the check is the same three questions: can two teams add a rule without a meeting, does the shipped CSS track what readers see, and can you change a theme without touching components?

One more thing to decide early is the exit. Strategies are not marriages: an app can move component by component, because modules, utilities and layers all compile down to ordinary CSS that ordinary rules can migrate. What matters is that the choice is written down — a short decision note naming the strategy, the token integration and the escape hatch policy — so the next person inherits a system rather than an accident.

06. Check your understanding

Practice check · 3 questions

Strategy trade-offs

Predict what each approach does in these situations.

Q1. A reset lives inside `@layer reset`. A rule with no layer at all sets the same property on the same element. Who wins?
Q2. A team adopts CSS Modules across a large app. Which problem does that adoption leave untouched?
Q3. A team proposes a run-time CSS-in-JS library for the design system. Which is the strongest practical objection?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the app you use in the skill's practice task:

  1. Write down its current strategy in one sentence. Then answer the three check questions above it: two teams, one rule; shipped CSS versus rendered UI; theme change without touching components.
  2. Build the two Tailwind CLI cases from this lesson with your own pages and compare the byte counts. As long as new screens mostly reuse existing classes, the growth per screen should stay small in your numbers too.
  3. Add a layer statement to one real stylesheet: @layer reset, base, components; and move existing rules into layers without changing any declaration. Any behaviour change you can measure is a bug in your ordering assumptions.

08. Review prompt

Without looking back: what does a bundler's CSS Modules pipeline change about class names, and what does it leave exactly as it was? Why does a utility framework's stylesheet grow slowly once the product is large? And where do cascade layers sit relative to specificity when two rules conflict?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check