Skip to content

    Frontend System Design

    CSS Architecture: Cascade, Layers, Methodologies and Utility-First

    How the CSS cascade, specificity and layers decide which rule wins, and how BEM, CSS Modules, utility-first CSS and @scope keep stylesheets predictable.

    By Published 12 min read

    • frontend-system-design
    • css
    • cascade-layers
    • css-architecture
    Share

    Standard lessonintermediateFrontend System Design

    Before this: HTML, CSS and JavaScript Architecture: Structuring a Large Interface

    What you'll learn: By the end of this lesson you will be able to explain how the browser picks one winning declaration (importance, layers, specificity, proximity, order), calculate specificity by hand, use cascade layers so that rule order beats selector strength, compare BEM, CSS Modules, utility-first CSS and @scope honestly, and design a stylesheet structure that a team of several squads can change without !important wars.

    Think of a shared office whiteboard. At first one person writes on it and everything is tidy. Then ten people write on it, each wants their note read first, and the loudest marker wins. That is a global stylesheet at scale. The fix is not a better marker but an agreed rule about who gets which part of the board, written into the board's own structure.

    The running example is the storefront of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a product card, a header, a checkout widget from a payment provider, and four squads that all ship CSS.

    The core idea

    1. CSS is a conflict-resolution system. Many rules can match one element. The cascade is the fixed procedure that picks one value per property. Architecture is the art of making that procedure produce the answer you intended.
    2. Selector strength is a weak tool for ordering rules. The only way to beat a strong selector is a stronger one. Cascade layers decide order explicitly, before specificity is looked at.
    3. Scope what should not leak. BEM, CSS Modules, utility classes and @scope are four ways to keep one component's styles from colliding with another's, with different trade-offs.

    How the browser picks a winner

    MDN describes the cascade as a series of steps. It keeps only the rules that apply to the element, sorts them by importance (!important or not) and origin, then by specificity (the highest wins). On a specificity tie, the scope with the fewest hops up the DOM to its scope root wins (scoping proximity). Order of appearance matters only when everything above is equal: the last declaration wins.

    Cascade layers sit in the importance step. MDN's @layer page says that once layer order is established, specificity and order of appearance are ignored between layers.

    Figure 1. Which declaration wins

    flowchart TD accTitle: Order in which the cascade compares matching declarations accDescr: A top-to-bottom decision flow. First keep only matching rules. Then compare importance and origin. Then compare cascade layers, where unlayered normal rules beat layered ones. Then compare specificity. Then compare scoping proximity. If all are equal, the last declaration in source order wins. A["Keep rules whose selector
    matches the element"] --> B["Importance and origin
    (normal vs !important)"] B --> C["Cascade layers
    (unlayered normal beats layered)"] C --> D["Specificity
    (ids, classes, types)"] D --> E["Scoping proximity
    (fewest hops to scope root)"] E --> F["Order of appearance
    (last declaration wins)"]

    How to read this: go down until one declaration is ahead; the steps below it are never consulted. That is why a layer can beat a rule with a much stronger selector, and why source order is the last resort, not the first.

    Specificity, calculated by hand

    MDN gives specificity as three columns compared from left to right. Each ID selector adds 1-0-0. Each class, attribute selector or pseudo-class adds 0-1-0. Each type selector or pseudo-element adds 0-0-1. The universal selector and :where() (with its arguments) contribute 0-0-0, and combinators add nothing. :is(), :not() and :has() add no weight themselves, but their arguments do: the weight is that of the most specific argument. Native CSS nesting works like :is(). Inline styles beat normal author rules; only !important overrides them, which MDN calls a bad practice for overriding specificity.

    The columns are compared left to right and do not carry over: one ID beats any number of classes.

    Illustration 1: the minimal example

    A small model of the comparison, using weights taken from the worked examples in MDN's specificity page (the weights are typed in by hand, the program only compares them). Run in Node:

    const rules = [
      { selector: "[type=\"password\"]", weight: [0, 1, 0] },
      { selector: "input:focus", weight: [0, 1, 1] },
      { selector: ":root #myApp input:required", weight: [1, 2, 1] },
      { selector: ":where(.card) a", weight: [0, 0, 1] },
      { selector: ".card .title", weight: [0, 2, 0] },
    ];
    const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
    for (const r of rules) console.log(r.selector.padEnd(30), r.weight.join("-"));
    const sorted = [...rules].sort((x, y) => compare(y.weight, x.weight));
    console.log("winner:", sorted[0].selector);

    Output, from running it in Node 26.13.1:

    [type="password"]              0-1-0
    input:focus                    0-1-1
    :root #myApp input:required    1-2-1
    :where(.card) a                0-0-1
    .card .title                   0-2-0
    winner: :root #myApp input:required

    The :where(.card) a line shows the point of :where(): the class inside it adds nothing, so the selector weighs the same as a bare a and is easy to override.

    Cascade layers: order you decide

    A cascade layer is a named bucket of rules whose priority is set by declaration order. MDN says the first declared layer has the lowest priority and the last declared layer the highest, and that re-declaring a layer name later appends rules to it without changing the order. Layers can be nested (framework.layout) and anonymous (no name, so rules cannot be added later).

    Two rules make layers useful and surprising:

    • Unlayered normal styles beat layered ones. MDN: styles not defined in a layer always override styles in named and anonymous layers.
    • !important reverses the order. The order of precedence among important rules is the inverse of normal rules, so an important declaration in an earlier layer beats an important one in a later layer, and important layered declarations beat important unlayered ones.

    A stylesheet can also be pulled into a layer with @import "theme.css" layer(utilities);. MDN notes that an @import must come before other rules except @charset and @layer statements.

    Figure 2. A layer order for the storefront

    Layer order from lowest to highest priorityvendor to reset and base (loses to); reset and base to tokens (loses to); tokens to components (loses to); components to utilities (loses to); utilities to unlayered (loses to)vendor: third-party CSSvendorthird-party CSSreset and base: element defaultsreset and baseelement defaultstokens: custom propertiestokenscustom propertiescomponents: cards, headercomponentscards, headerutilities: hidden, stackutilitieshidden, stackunlayered: beats every layerunlayeredbeats every layerloses toloses toloses toloses toloses to

    How to read this: an arrow points to the layer that wins when both set the same property, whatever the specificity. The warning box is the trap: any rule outside a layer, including a stray <style> tag, outranks all of them for normal declarations.

    Illustration 2: the realistic example

    The storefront declares its order once, first in the entry stylesheet, then each squad writes inside its own layer:

    @layer vendor, reset, tokens, components, utilities;
    
    @layer tokens {
      :root {
        --space-2: 0.5rem;
        --color-accent: #9c4521;
      }
    }
    
    @layer components {
      .product-card { display: grid; gap: var(--space-2); }
      .product-card .price { color: var(--color-accent); }
    }
    
    @layer utilities {
      .hidden { display: none; }
    }

    A product card with class="product-card hidden" is hidden. .product-card sets display: grid with specificity 0-1-0, .hidden sets display: none with the same weight, but utilities is declared after components, so layer order decides before specificity or source order is ever compared. No !important is needed, and no squad has to know who wrote the file first.

    The tokens are CSS custom properties. MDN says a property declared with two dashes always inherits from its parent, is computed where it is needed, and var(--name, fallback) supplies a fallback when the property is invalid. Note the fallback is not a compatibility fix for browsers that lack custom properties.

    Keeping component styles from colliding

    Layers order rules; they do not stop two components both defining .title. Four common approaches:

    • A naming convention (BEM). The BEM naming page writes names as block__element_modifier_value, with a double underscore before an element and a single underscore before a modifier; an element cannot contain another element in its name (block__elem1__elem2 is not valid). Collisions are avoided by discipline. Caution from MDN's nesting guide: Sass-style &__child concatenation does not work in native CSS nesting.
    • CSS Modules. The project README defines a CSS Module as a CSS file where all class names and animation names are scoped locally by default; importing one into JavaScript exports an object that maps local names to global names. The tool, not the author, avoids collisions.
    • Utility-first CSS. Tailwind's documentation describes it as combining many single-purpose presentational classes directly in markup. Its listed benefits: no time spent naming, a change affects only that element, and the stylesheet stops growing with every feature. It recommends components or template partials for repetition, and never adding two conflicting classes to one element. Custom utilities go in a utilities layer, with @layer base and @layer components for the rest.
    • @scope. MDN says it selects elements in specific DOM subtrees without overly specific selectors, with an optional lower limit (a "donut scope"). Selectors inside behave as if :where(:scope) were prepended, so they add zero weight, and it adds the scoping-proximity step to the cascade. At the time of writing MDN shows it as Baseline 2026, newly available since March 2026; check support before relying on it for older browsers.

    Figure 3. Choosing a scoping approach

    flowchart TD accTitle: Choosing how to scope component styles accDescr: A decision flow. If the team ships a component library across frameworks, prefer a naming convention and custom properties. If a build step with JavaScript imports exists, CSS Modules scope class names automatically. If designers want constrained tokens and fast iteration, utility-first fits. Use at-scope for subtree rules once the support check passes. A{"Is there a
    build step?"} A -->|"no"| B["Naming convention (BEM)
    + layers + custom properties"] A -->|"yes"| C{"Own the markup
    of every page?"} C -->|"yes, component-driven"| D["CSS Modules
    or utility-first"] C -->|"no, mixed or CMS content"| E["Layers + @scope
    on the content region"] D --> F["Declare layer order
    once, first"] B --> F E --> F

    How to read this: the questions are about constraints, not taste. Every branch ends at the same layer declaration, so layers are the base and the scoping tool is a choice on top.

    Illustration 3: a failure, unlayered beats layered

    A model of the layer rule for normal declarations, to make the surprise visible. The ranking is the one MDN states (later layer wins, unlayered beats all layers); specificity only breaks ties inside a layer. Run in Node:

    const order = ["reset", "components", "utilities", "(unlayered)"];
    const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
    const cases = [
      { who: "utilities", weight: [0, 0, 1] },
      { who: "components", weight: [1, 0, 0] },
      { who: "(unlayered)", weight: [0, 0, 1] },
    ];
    const rank = (c) => order.indexOf(c.who);
    const winner = [...cases].sort((a, b) => rank(b) - rank(a) || compare(b.weight, a.weight))[0];
    for (const c of cases) console.log(c.who.padEnd(14), "specificity", c.weight.join("-"));
    console.log("winner (normal declarations):", winner.who);

    Output, from running it in Node 26.13.1:

    utilities      specificity 0-0-1
    components     specificity 1-0-0
    (unlayered)    specificity 0-0-1
    winner (normal declarations): (unlayered)

    The components rule has an ID in its selector (1-0-0) and still loses to a plain a-weight rule that sits outside any layer. A team that adopts layers for new code and leaves older CSS unlayered finds the old code wins everywhere.

    Trade-offs

    Choice Gain Cost
    Cascade layers with a declared order Order is explicit; no specificity arms race Unlayered CSS silently wins; everyone must learn the reversal for !important
    BEM No tooling needed; readable in DevTools Long names; collisions prevented only by discipline
    CSS Modules Automatic local scope A build step; sharing styles needs imports or a global layer
    Utility-first Fast to change, stylesheet stops growing Long class lists in markup; needs a component habit to avoid repetition
    @scope Subtree rules with zero added weight Newer feature; check browser support; proximity is one more rule to learn
    Custom properties as tokens One place to change a value; they inherit Computed where used; no fallback for browsers without support

    Build it

    This lesson has no lab. The three small Node snippets above are plain JavaScript and need no install; they model the comparison rules and do not run a browser, so they say nothing about rendering. No browser check was performed here, so no browser output is shown.

    In practice: the storefront stylesheet

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    Four squads (catalogue, cart, account, marketing) ship CSS into one global stylesheet of several hundred files (illustrative). A payment provider's widget adds its own stylesheet. !important has crept into about one rule in ten (illustrative), a shared button needs three chained classes to beat another squad's rule, and a header redesign breaks the cart page because both used a .title class.

    Starting architecture

    Figure 4. One global cascade

    Starting architecture: every squad writes into one global cascadeCatalogue CSS to One cascade; Cart CSS to One cascade; Marketing CSS to One cascade; Payment widget to One cascade; One cascade to Rendered pageCatalogue CSS: global classesCatalogue CSSglobal classesCart CSS: global classesCart CSSglobal classesMarketing CSS: important usedMarketing CSSimportant usedOne cascade: specificity winsOne cascadespecificity winsPayment widget: own stylesheetPayment widgetown stylesheetRendered page: collisionsRendered pagecollisions

    How to read this: the warning boxes are where order is decided by selector strength and !important. Any new rule has to out-shout every older one that might match.

    Options considered

    Option What it fixes What it costs Risk
    Rewrite everything as utility classes Removes naming collisions A large migration; a Tailwind-style toolchain Mixed old and new CSS during migration
    Layers for order, CSS Modules for components, tokens as custom properties Order and scope fixed separately; migration can be gradual Learn layers; move old CSS into a layer Unlayered leftovers win silently

    The decision

    Field Decision record
    Context Four squads share one global cascade and fight with specificity and !important.
    Decision Declare @layer vendor, reset, tokens, components, utilities; first. Move old CSS into components with @import ... layer(...). New components use CSS Modules. Shared values become custom properties in tokens.
    Consequences, good Order is explicit; a utility beats a component without a strong selector; migration is per file.
    Consequences, bad Everyone must learn that unlayered CSS beats layers; two systems coexist during migration.
    Revisit when Most code is in layers (consider dropping the global components bucket), or @scope support covers your audience.

    Figure 5. Target architecture

    Target architecture: layers decide order, modules decide scopevendor layer to components layer (lower priority); tokens layer to components layer (values); components layer to utilities layer (lower priority); utilities layer to Rendered pagevendor layer: widget CSSvendor layerwidget CSStokens layer: custom propertiestokens layercustom propertiescomponents layer: CSS ModulescomponentslayerCSS Modulesutilities layer: last, wins tiesutilitieslayerlast, wins tiesRendered page: predictableRendered pagepredictablelower priorityvalueslower priority

    How to read this: the same four writers, now separated by layer. The vendor widget sits at the bottom, so our component styles can restyle it without raising specificity.

    Rollout and verification

    1. Add the layer declaration and put the old stylesheet in components. List the unlayered leftovers, which now beat it (CSS outside @layer, including injected <style> tags).
    2. Import vendor CSS into vendor. Check the widget renders and your overrides no longer need extra selectors.
    3. Remove !important one rule at a time, using layer placement instead; remember the reversal for important declarations.
    4. Check the winning rule for the most-touched components.
    5. Add a lint rule rejecting new unlayered CSS and new !important.

    The 2 a.m. failure

    After a marketing change, a third-party tag manager injects a <style> block with button { background: green }, outside any layer. Every button in the storefront turns green, including the red "Remove from cart" buttons, because unlayered normal rules outrank all layered ones.

    First three checks: (1) inspect a button in DevTools and see which rule won and whether it is layered; (2) look for style tags or stylesheets added by scripts; (3) check whether the change shipped with a recent tag change. Mitigation: disable the tag, or add an override for the affected selectors outside any layer. Follow-up: ask the vendor to scope its CSS, load its stylesheet through @import ... layer(vendor) when it is a file you control, and isolate widgets that insist on global styles.

    Architect's notes

    • Declare layer order once, at the top, in a file someone owns.
    • Prefer layers to specificity for ordering; keep selectors flat and use :where() in shared code.
    • Treat unlayered CSS as the highest tier, because it is. Audit for it.
    • Name tokens for meaning (--color-accent), not for value.
    • Pick one scoping tool per code base. The component-based architecture and feature-based folder structure lessons describe where such a rule belongs.

    Common mistakes

    • Fixing a losing rule with a longer selector or !important. It works once and raises the bar for everyone after.
    • Adopting layers and leaving old CSS unlayered. The old CSS now wins everywhere.
    • Forgetting that !important reverses layer order.
    • Using @scope or nesting without checking support for your audience.
    • Writing &__child in native CSS nesting and expecting Sass behaviour.
    • Putting conflicting utilities on one element (p-2 p-4) and hoping the later one wins.

    Key takeaways

    • The cascade compares importance and layers first, then specificity, then proximity, then order.
    • Specificity is three columns compared left to right; :where() weighs nothing, :is() and :not() take their strongest argument.
    • Layers order rules by declaration order; unlayered normal rules beat all layers, and !important reverses the layer order.
    • BEM, CSS Modules, utility-first and @scope all scope styles; choose one and say why.
    • Custom properties inherit and are computed where used, so they work as design tokens.
    • A migration to layers must find and handle unlayered CSS, including injected style tags.

    Practice exercises

    Exercise 1: Starter (30 min). Compute the specificity of nav ul li a:hover, #menu .item and :is(.a, #b) p by hand, then check the weights against MDN's rules.

    Exercise 2: Intermediate (2 hours). Extend the Illustration 3 script with a fourth layer and an !important case using the reversal rule, and write down the output you predict before you run it.

    Exercise 3: Advanced (half day). Take an existing stylesheet and list every rule that is not inside a layer and every !important. Propose a layer order and a migration order, and explain which entries you would leave until last.

    In this course:

    Companion lessons in this module, named here in plain text: HTML, CSS and JavaScript architecture; semantic HTML and document structure; modern CSS layout and responsive design.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments