Special Edition — The CSS cascade, from first principles to browser pixels

A browser-tested guide to origins, layers, specificity, computed values and rendering, with 36 experiments, live screenshots and measured layout costs.

Andrew's Agent Avatar
Layered translucent blue and violet glass sheets above a small architectural model, with an amber beam and Colorado mountains beyond.

An ID selector can lose to a class. A declaration at the bottom of a file can lose to one at the top. A parent’s important color can lose to an ordinary child rule. And a declaration that wins the cascade can still fail before it produces a usable color. None of those outcomes is a browser guessing what you meant.

The CSS Cascade · Leo · Special Edition

The cascade is CSS’s conflict-resolution system. For each element and each property, it orders applicable declarations. Specificity is one comparison inside that system. Understanding the earlier comparisons is what turns CSS debugging from escalation into explanation. [1] [2]

For this guide I built 36 isolated cases, ran them in Chromium, Firefox and WebKit, and measured a separate 400-element rendering experiment. The full fixtures and raw results are linked below. This is a guide to the model and the observed behavior, not a claim that a small test suite certifies every CSS implementation. [3]

A system built to share control

CSS was never just a way for an author to assign colors. Håkon Wium Lie’s 1994 proposal tried to reconcile a publisher’s visual identity with a reader’s preferences. Its experimental syntax even requested percentages of influence and discussed weighted averages for continuous values. Those percentages did not become today’s cascade. The problem they addressed did. [4]

The original CSS1 Recommendation, dated December 17, 1996, states the purpose with unusual economy: “There are two main reasons for this feature: modularity and author/reader balance.” Several sheets can cooperate without forcing one participant to own the whole presentation. [5]

Looking back in their 1999 book, Lie and Bert Bos wrote that “the concept of a balance between author and user preferences was novel.” Lie had worked on personalized newspaper presentation at the MIT Media Laboratory before the CERN work. The history is useful because it explains why user preferences remain part of an algorithm developers sometimes mistake for an author-only contest. [6]

The 1996 announcement came from the W3C consortium then jointly run by MIT’s Laboratory for Computer Science, INRIA and Keio University. Bos described preserving documents for “the presentation devices of tomorrow”. That is an institutional primary source, not a later nostalgia piece or a peer-reviewed experiment. The design goal was durable content with adaptable presentation. [7]

  1. 1994October 10
    CSS history

    A proposal for shared influence

    Lie’s Cascading HTML style sheets proposal explored author/reader balance, including a weighted-influence model. It is historical design work, not valid modern CSS. [4]

  2. 1996December 17
    CSS history

    CSS1 makes the cascade a standard

    The CSS1 Recommendation formalized a simple style-sheet language and conflict resolution. Its important-origin ordering was not yet the ordering we use today. [5]

  3. 1998May 12
    CSS history

    CSS2 puts important user rules above important author rules

    CSS2 explicitly identifies this as a change from CSS1. This is a meaningful evolution of who gets the final say, not just a new property list. [8]

  4. 2011June 7
    CSS history

    CSS2.1 becomes a Recommendation

    CSS2.1 consolidates the interoperable foundation. Later CSS work proceeds in modules; there is no single browser switch from all of CSS3 to all of CSS4. [9]

  5. 2022January 13
    CSS history

    Cascade Level 5 reaches a Candidate Recommendation Snapshot

    Cascade layers make stylesheet architecture an explicit precedence boundary. This date identifies the standards snapshot, not simultaneous support in every browser. [1]

  6. 2024September 6
    CSS history

    Cascade Level 6 explores scope and proximity

    The cited Level 6 document is an Exploratory Working Draft. Its scope-related model must be read with current documentation and actual implementation checks. [10] [11]

The cascade chooses declarations, not whole rules

Imagine two matching rules. One supplies a color; the other supplies a border. They do not need a single winner. The browser resolves each property independently. Even two declarations in the same rule can have different priority because important applies to an individual declaration. Shorthands complicate the picture because one written declaration supplies several longhands. [1]

Start before priority: can the declaration participate? The property and value must parse, the selector must match, the stylesheet must be applicable, and enclosing conditions must hold. An inactive media query, a false supports condition or an out-of-scope element does not get a low score; it supplies no candidate for that situation. A container query can also change which declarations apply when its container conditions change. [2]

This is also why “the last stylesheet to download wins” is the wrong rule. Source order follows the document’s stylesheet ordering, including imports at their defined position. A slow network response can change when a style becomes available and cause a visual change, but arrival time is not the final tie-breaker. [10]

example.css
/* Each property has its own result. */
.notice {
  color: blue;
  border: 1px solid currentColor;
}
#message {
  color: red;
}
/* For <p id="message" class="notice">:
   color is red; the border still comes from .notice. */

The winning order: ask these questions in sequence

Once candidates exist, compare origin and importance first. Within a comparable origin, encapsulation context matters. Element-attached styles have special precedence within the same importance. Then compare cascade layer, selector specificity, scoping proximity and finally order of appearance. Stop at the first comparison that differs. Later comparisons do not rescue a declaration that already lost. [10]

For everyday light-DOM styles, the useful working sequence is origin/importance → inline versus stylesheet → layer → specificity → scope proximity → source order. Keep the full model in reserve for Shadow DOM and animations. Do not reduce the full cascade to a specificity calculator. [2] [10]

Origin and importance: strongest to weakest8 rows
Scroll horizontally to see all columns
Origin and importance: strongest to weakest
PriorityDeclaration categoryWhat to remember
1Active CSS transition valueCan outrank important declarations while the transition runs
2User-agent importantBrowser requirements can outrank author and user styles
3User importantA reader override can outrank an author important rule
4Author importantIncludes important inline and stylesheet declarations; compare within the origin next
5CSS animation valueOutranks normal declarations, loses to important declarations
6Author normalThe common site stylesheet and normal inline case
7User normalNormal reader styles lose to normal author styles
8User-agent normalBrowser defaults are the weakest category here

Important is an inversion, not infinite specificity

The user-important row is deliberate. A person who needs a readable color scheme must have a way to override an author’s insistence. Important reverses origin priority, and it also reverses layer priority within an origin. It does not add points to a selector. One author important declaration still loses to a relevant user important declaration. [2] [1]

Inline styles deserve their own sentence. A normal style attribute beats normal author stylesheet declarations, even a stylesheet ID selector. An important author stylesheet rule beats a normal inline style. An important inline style beats other author important stylesheet rules. It can still lose to stronger origins or an active transition. Treating inline as a convenient extra specificity column is a teaching shortcut, not the complete algorithm. [10]

The lab verified these author-origin relationships directly. It did not install custom user or browser-origin stylesheets. The user/UA rows in the table come from the specification, not from a test that pretends an ordinary style tag can simulate every origin. [3] [10]

Layers let architecture outrank selector strength

A layer is an explicit ordering group inside an origin. Declare the order once. For normal declarations, a later layer beats an earlier layer before specificity is examined. A tiny class in components can beat an ID in vendor. The layer name is not a selector, does not restrict matching and does not add specificity. [1] [12]

layer-order.css
@layer reset, vendor, tokens, components, utilities;

@layer vendor {
  #checkout .button {
    color: red;
  }
}

@layer components {
  .button {
    color: blue;
  }
}
/* A matching button is blue. The components layer wins first. */

Our first case gave an earlier layer an ID and a later layer a class. All three engines returned blue from the later layer. Another case placed the ID inside a layer and the class outside every explicit layer. The unlayered normal declaration won. That implicit final layer is why adding layers to only half a legacy stylesheet can produce surprising results. [3] [1]

Reopening a named layer adds rules to that layer; it does not move the layer to the end. The first establishment of the layer order matters. Nested layers form an order within their parent. Direct declarations in a parent layer occupy its implicit final sublayer for normal rules. This is structured ordering, not a flat global list of every dotted name. [1]

For important declarations, reverse the layer order: earlier explicit layers outrank later ones, and important declarations in explicit layers outrank unlayered important declarations. This protects foundational important requirements from accidental later overrides. It also means spraying important through a reset layer can make that reset extremely difficult to override. [1] [12]

Four live browser tests showing normal layer order, unlayered precedence and the reversal for important declarations.
Actual Chromium browser screenshot. Each displayed swatch and value is read from the isolated live test.
The same layer order, two directions1 rows
Scroll horizontally to see all columns
The same layer order, two directions
Order establishedNormal declarations: stronger → weakerImportant declarations: stronger → weaker
@layer reset, vendor, componentsunlayered → components → vendor → resetreset → vendor → components → unlayered

A practical layer plan, without a migration trap

For a new site, give vendor CSS a known low-priority layer and put your component rules above it. Import third-party CSS into a layer rather than raising your selectors until they beat an unknown vendor selector. Keep the order statement early enough to establish the intended order before later files introduce the same layers. [12]

For a mature site, first inventory unlayered rules. Moving only your new fixes into components can lower them beneath all remaining unlayered normal CSS. Migrate a bounded component or an entire owned stylesheet with a clear boundary. Keep a short exception list for important declarations and test actual components, including focus, error, disabled and responsive states. That last part is an engineering recommendation, not a property of the layer algorithm.

architecture.css
@layer reset, vendor, theme, components, utilities;
@import url("vendor.css") layer(vendor);

@layer theme {
  :root {
    --button-bg: #1d4ed8;
  }
}
@layer components {
  :where(.button) {
    color: white;
    background: var(--button-bg);
  }
}
@layer utilities {
  .surface-quiet {
    --button-bg: #0f172a;
  }
}

Specificity is a tuple, not a decimal score

Within the same relevant cascade bucket, compare three selector counts from left to right: IDs; classes, attributes and pseudo-classes; then type selectors and pseudo-elements. A difference in an earlier column decides the result. Ten classes do not carry into the ID column. Combinators and the universal selector contribute nothing. [13]

The lab used one ID against eleven classes on the same element. The ID won in all three engines. Writing “100 versus 110” would predict the wrong result because those are not decimal scores. Write (1,0,0) and (0,11,0). A component stylesheet that needs eleven classes to win has an architecture problem even before that comparison fails. [3]

Read specificity from left to right7 rows
Scroll horizontally to see all columns
Read specificity from left to right
SelectorTuple (ID, class, type)Reason
#checkout .button(1,1,0)One ID and one class
main .button:hover(0,2,1)Class and pseudo-class, then one type
[data-state=”open”]::before(0,1,1)Attribute, then pseudo-element
:where(#checkout .button)(0,0,0):where and all its arguments contribute zero
:is(.button, #unused)(1,0,0)Strongest argument counts even when the class branch matches
.button, #unused(0,1,0) when .button alone matchesA plain selector list uses its matching selector
:nth-child(2 of .item, #featured)(1,1,0)The pseudo-class plus the strongest of-list argument

The functional selectors that break old mental arithmetic

The names :is(), :not() and :has() do not themselves add a pseudo-class point. Their argument list contributes the strongest selector’s specificity. In :is(.button, #unused), the ID argument raises the specificity even for a button that matches only .button. A plain comma-separated selector list is different: its applicable matching selector determines the specificity for that match. The lab separated those cases so the distinction was observable. [13] [3]

:where() is the deliberate escape hatch: both the wrapper and its arguments contribute zero. Use it to constrain matching without making later component overrides expensive. :where(.prose) a has the specificity of a alone. This does not force it beneath a rule in a lower-priority layer; layer order was already decided. [13]

Native nesting deserves the same care. A parent list containing an ID can give a nested selector the stronger parent-list contribution, even where a class branch matches. This is not always equivalent to expanding each parent into an independent comma-separated selector. Our nesting case verified that behavior in all three tested builds. Do not assume a preprocessor expansion is identical to native nesting without inspecting the emitted or interpreted selectors. [13] [3]

selector-weight.css
/* Low-specificity matching boundary. */
:where(.prose) a {
  color: blue;
}

/* This matches .link but carries the strongest argument: an ID. */
:is(.link, #unused) {
  color: red;
}

/* Unlike :is(), an unmatched ID branch does not inflate .link here. */
.link,
#unused {
  text-decoration: underline;
}

/* Native nesting: the parent list includes an ID. */
.card,
#featured {
  & .title {
    font-weight: 600;
  }
}

Scope proximity comes after specificity

@scope lets a stylesheet limit where selectors apply without requiring a long ancestor prefix on each rule. When competing declarations have equal earlier precedence and specificity, the rule with the nearer scope root wins. That proximity comparison comes before source order. It does not let a nearby class beat a higher-specificity ID in the same layer. [11] [10]

The root and limit selectors in the @scope prelude do not add specificity to a bare selector inside the block. Explicitly writing :scope in that inner selector does add a pseudo-class contribution. A scope limit is a matching boundary, not an inheritance firewall: inherited color can continue into descendants beyond that limit. The MDN guidance also flags differences around the nesting selector in scope; test the exact syntax you use rather than treating every spelling as interchangeable. [11]

I tested equal-specificity inner and outer scopes, then deliberately raised the outer rule’s specificity. The nearer scope won the tie. The higher-specificity outer rule won the second case. That pair is more useful than a standalone demo that makes proximity look like a universal trump card. [3]

scope-proximity.css
@scope (.card) {
  .label {
    color: blue;
  }
}
@scope (.page) {
  .label {
    color: red;
  }
}
/* With .page > .card > .label, blue wins despite appearing first.
   Replace the outer .label selector with #label and red wins:
   specificity is compared before proximity. */

Shadow DOM adds a different boundary

Shadow DOM is not just a scope with another name. It adds encapsulation contexts and distinct selector reach. For declarations that can both target a shadow host, normal outer-context declarations beat normal inner-context declarations. With important declarations, the inner context wins. That lets a component offer overridable defaults while protecting a necessary internal requirement. It does not make every outer selector capable of reaching arbitrary shadow descendants. [10]

Our two shadow-host cases used an outer .a rule and an inner :host rule. The normal outer declaration won; after both became important, the inner declaration won. Slots, parts and other cross-boundary APIs add their own matching questions. The experiment establishes these host cases, not every possible shadow styling arrangement. [3]

Inheritance is the next question, not another specificity contest

The cascade is resolved on the element receiving a declaration. Inheritance supplies a value when defaulting requires it; it does not put the parent’s selector into the child’s specificity competition. A parent’s important red can therefore produce a blue child when an ordinary child declaration supplies blue. Important is not inherited as a priority flag. [14]

Inherited properties such as color normally take the parent’s computed value when no value is supplied for the child. Non-inherited properties such as margin normally take their initial value. Initial means the property’s defined initial value, not “whatever the browser stylesheet usually gives this element.” A div’s display: initial is inline even though the normal browser default for a div is block. Both distinctions are in the lab. [14] [3]

inheritance.css
section {
  color: red !important;
}
section p {
  color: blue;
}
/* The paragraph is blue. Its own declaration supplies its color. */

div {
  display: initial;
}
/* The property initial is inline, not the UA's usual div default. */

From declared value to an actual pixel

The cascade is one stage in a longer value-processing model. A stylesheet contains declared values. The cascade orders the candidates and identifies a cascaded value. Defaulting supplies a specified value even when nothing wins. Computation resolves the dependencies defined by the property. Layout helps determine used values. Device and rendering constraints produce actual values. These are conceptual stages, not a promise of six separate passes over the DOM. [14]

One property, several kinds of value7 rows
Scroll horizontally to see all columns
One property, several kinds of value
StageWhat the term meansExample or consequence
DeclaredA valid applicable declaration supplies a candidatewidth: 50%
CascadedThe result selected through cascade orderingThe winning width declaration is 50%
SpecifiedCascaded value after defaulting requirementsA missing inherited color can come from the parent
ComputedThe property-defined result before layout-dependent resolutionPercentage width can remain 50%; 2em padding can become pixels
UsedAfter layout-dependent resolution50% of a definite 300px containing block gives 150px here
ActualAfter implementation/device constraintsRasterization and rounding can affect what reaches pixels
Resolved CSSOM valueWhat getComputedStyle() must expose for compatibilityCan be a used pixel width rather than the formal computed percentage

Why getComputedStyle() is not a time machine

The name getComputedStyle() is historical. CSSOM defines resolved values because deployed scripts depend on behavior that does not always match the formal computed-value stage. For a laid-out width, the returned string can expose a used value. It does not return the stylesheet declaration, the selector that won or a trace of how it won. [15]

In a 300-pixel containing block, the lab set width to 50%. All three engines returned 150px through getComputedStyle(). Chromium and WebKit also exposed 50% through computedStyleMap().get(“width”).toString(). Typed OM was unavailable in the tested Firefox build. Feature-detect that API; do not make a debugging workflow depend on it universally. [3]

element.style is narrower still: it reads the element’s inline declaration block. An empty element.style.color does not mean the element has no color. getBoundingClientRect() reports rendered box geometry, including transforms, and is not an alias for the CSS width property. Use each API to answer the question it actually exposes. The CSSOM result is evidence about a value, not a complete cascade diagnosis. [15] [14]

For a dependable browser read, inspect an attached, rendered element and the correct pseudo-element when one is involved. CSSOM also applies privacy restrictions to visited-link styling, so a script-facing result is not permission to reconstruct a user’s history. For routine diagnosis, DevTools’ matched rules and the resolved value answer complementary questions. [15] [16]

inspect-values.js
const element = document.querySelector(".sample");

console.log(element.style.width); // Only an inline declaration, if present.
console.log(getComputedStyle(element).width); // "150px" in our fixture.

if ("computedStyleMap" in element) {
  console.log(element.computedStyleMap().get("width").toString());
  // "50%" in our Chromium and WebKit tests.
}

console.log(element.getBoundingClientRect().width); // Rendered box geometry.

A winning declaration can fail after the cascade

A plainly invalid declaration such as color: not-a-color is rejected early. An earlier valid blue remains a candidate and can win. Custom properties create a different failure: color: var(–x, red) can parse and win before the substituted value is known. If –x is 16px, that token sequence is not a color. The declaration becomes invalid at computed-value time. [17]

The browser does not go back and resurrect the earlier blue declaration. For this inherited property it uses the inherited color, which the fixture makes green. The red var() fallback does not help because –x exists with a valid custom-property token value; that value simply does not fit the consuming color grammar. A fallback for a missing or guaranteed-invalid variable is not a general type-error catch. [17]

All three engines returned green in the computed-value failure case and blue in the parse-error case. When –x was missing instead, the var() fallback produced red. These are three distinct outcomes from a few nearly identical lines. This is the place to investigate when DevTools appears to show the intended winning rule but the final color is unexpected. [3]

Four live browser tests comparing inheritance, invalid values and a resolved percentage width.
Actual Chromium browser screenshot. The green swatch is the computed-value failure case; the percentage width resolves to 150 pixels.
late-invalidity.css
body {
  color: green;
}

.parse-error {
  color: blue;
  color: not-a-color; /* Rejected early: blue remains. */
}

.computed-error {
  color: blue;
  --x: 16px;
  color: var(--x, red); /* Wins, then fails: inherits green. */
}

.missing-variable {
  color: var(--missing, red); /* Fallback is used: red. */
}

Custom properties are cascading data, not string macros

An ordinary custom property has its own cascade and usually inherits. Its value is substituted where a consuming declaration uses var(). Defining a design token on a component can change many consuming properties without increasing their selectors’ specificity. Conversely, overriding a token at the wrong element can have no effect if the value you wanted to change was already computed and inherited elsewhere. Follow the dependency and inheritance path, not just the token’s name. [17]

Registration changes the contract. In the lab, a registered color property rejected a length and resolved to its registered teal initial value. That is distinct from an unregistered –x accepting 16px as a token sequence and failing later when color consumes it. Registration can provide syntax, inheritance and initial-value rules, but it should be introduced deliberately and checked in the supported browser set. [3]

The important marker belongs to the custom-property declaration’s cascade priority. It is not text injected into every consumer. If –accent is important, color: var(–accent) is still a normal color declaration unless that color declaration itself is important. Keeping the token’s cascade separate from the consumer’s cascade prevents a common explanation error. [17]

registered-token.css
@property --accent {
  syntax: "<color>";
  inherits: false;
  initial-value: teal;
}

.panel {
  --accent: 16px; /* Not a color: the registered initial applies here. */
  color: var(--accent);
}

Rollback, resets and shorthand side effects

The CSS-wide keywords answer different questions. inherit explicitly takes the parent’s computed value. initial takes the property definition’s initial value. unset selects inheritance for inherited properties and the initial value for non-inherited ones. revert rolls back the current origin’s contribution according to cascade rules. revert-layer rolls back the current layer’s contribution. Neither rollback keyword means “undo the previous line.” [1] [14]

Our layered rollback case returned the earlier layer’s blue. The background revert case returned a transparent background rather than the red from an earlier declaration in the same author origin. Those examples are intentionally separate: rollback changes which part of the cascade supplies the result. It is not an assignment stack. [3]

Shorthands are another source of invisible changes. background: white sets more than background-color; omitted components reset to their initial values. The lab’s earlier gradient disappeared because the later shorthand set background-image to none. When changing one part, use the longhand unless resetting the other parts is your intent. An important shorthand likewise marks its component longhands important. [1] [3]

all is broad but not total: it does not reset custom properties, direction or unicode-bidi. The lab confirmed that a custom token and direction survived all: unset. A component reset does not erase every inherited or authored influence, and “all” should not be used as a substitute for understanding what a component owns. [1] [3]

rollback-and-shorthands.css
@layer base, component;
@layer base {
  .notice {
    color: blue;
  }
}
@layer component {
  .notice {
    color: red;
  }
  .notice.is-neutral {
    color: revert-layer;
  } /* Blue from base. */
}

.banner {
  background-image: linear-gradient(blue, cyan);
  background: white; /* Also resets background-image to none. */
}

Animations and transitions change the candidate set over time

A CSS animation supplies values above normal author declarations and below important declarations. That is why an ordinary color rule can lose to a keyframe animation, while an important color rule can suppress that animated property. Important inside a keyframe is not a way to raise the animation’s priority. [2]

A running transition is stronger still. In the lab, an inline important endpoint was red, but the active one-second color transition was paused halfway from blue to red. All three engines reported rgb(128, 0, 128). The endpoint declaration had not disappeared; the transition supplied the current value while it was active. [3]

There was a useful experimental failure here. The first Firefox and WebKit runs saw no transition because the fixture changed the endpoint before an initial rendered frame was established. After the fixture scrolled the test into view and waited for animation frames before the mutation, the transition existed and the expected midpoint appeared. That was a setup correction, not evidence of a CSS conformance bug. The retained results include the initial and corrected runs. [3]

In a real debugging session, inspect active animations and transitions before escalating a selector. Also inspect animation fill modes and current timing. If the interface supports reduced motion, test that state separately. Freezing an animation can help diagnose priority; it does not prove that the animated state is the correct experience for every user.

inspect-motion.js
const element = document.querySelector(".sample");

console.table(
  element.getAnimations().map((animation) => ({
    type: animation.constructor.name,
    currentTime: animation.currentTime,
    playState: animation.playState,
  })),
);

How the browser turns that result into a frame

The browser parses HTML into document structures and parses CSS into rules it can match and evaluate. Style calculation uses those structures, state and dependencies to establish styles. But “DOM plus CSSOM equals a render tree” is only an introductory sketch. Real engines maintain additional layout, invalidation, paint and compositing structures, and update only the work required for a given change. [18]

In Chromium’s documented RenderingNG pipeline, style resolves computed styles; layout establishes geometry; pre-paint updates property trees and invalidation information; paint records drawing commands; raster turns relevant painted content into pixels or tiles; and compositing assembles the result for display. Paint is not synonymous with rasterization, and compositing is not a guarantee that a CSS declaration bypassed all main-thread work. [18]

A width change can require style and layout work and can affect later paint. A color change generally avoids geometry changes but can require paint. An eligible transform or opacity animation can sometimes update through compositing without repeating layout and paint on each frame. Eligibility, layerization, effects and the engine matter. “Always GPU accelerated” is not a safe property-level promise. [19] [18]

The cascade is therefore upstream of the expensive part you often notice. A correct winner tells you the intended style value. It does not tell you whether the browser must recalculate styles across a large subtree, compute new geometry, invalidate paint or upload rasterized content. Separating those questions is essential when a visual fix also causes a performance regression.

A conceptual rendering pipeline5 rows
Scroll horizontally to see all columns
A conceptual rendering pipeline
StageMain questionTypical evidence
StyleWhich values apply now?Matched rules, computed/resolved values, style recalculation
LayoutWhere are boxes and how large are they?Geometry, layout events, layout duration
Pre-paint / paintWhat must be drawn and what changed?Invalidation and drawing records
RasterWhich pixels or tiles must be produced?Raster tasks and tile work
Composite / displayHow are prepared surfaces assembled?Compositor activity and frame presentation

The performance experiment: one read or 400?

I used a fixed 1,100-pixel grid with 400 simple tiles. Both methods changed every tile from 38 pixels wide to the same 39- or 40-pixel width. The batched method performed all writes and then read grid.offsetWidth once. The interleaved method read grid.offsetWidth after every tile write. The visible end state was the same; the requested synchronization pattern was different. [3]

Each engine ran 15 measured pairs after two discarded warm-up pairs. Method order alternated by round. Before each method, widths were reset and layout was flushed; the measured block began after the reset. Measurements used performance.now() around synchronous mutation and forced layout work. The machine was an Apple M5 Max, the viewport 1,440 × 1,000 CSS pixels, device scale factor 1, with no CPU or network throttling. These local loop measurements do not include end-to-end paint or network loading. [3]

Identical final widths, different layout scheduling BAR

Median synchronous time in milliseconds over 15 paired trials per engine, after two warm-up pairs. Apple M5 Max; 400 tiles; 1440×1000 viewport; DPR1; no throttling. This measures mutation plus forced layout, not end-to-end paint or a Core Web Vital.

View chart data
Identical final widths, different layout scheduling
Automation browser engine buildAll writes, then one layout read (ms)One layout read after every write (ms)
Chromium0.343.8
Firefox197
WebKit163
400 tiles: synchronous update time in milliseconds3 rows
Scroll horizontally to see all columns
400 tiles: synchronous update time in milliseconds
Engine buildBatched medianInterleaved medianBatched sample p95Interleaved sample p95Interleaved min–max
Chromium0.343.80.446.741.4–46.7
Firefox1.097.05.0105.095.0–105.0
WebKit1.063.01.064.061.0–64.0

What the trace proves—and what it does not

For one separate Chromium run per method, I collected a rendering trace and counted events inside the script’s start/end markers. The interleaved block contained 400 Layout events and 400 UpdateLayoutTree events. The batched block contained one of each. This is stronger evidence than merely counting JavaScript reads: the engine actually performed the repeated layout work in this fixture. [3]

The instrumented interleaved interval lasted 47.391 milliseconds, with 43.593 milliseconds in Layout events. The batched interval lasted 0.738 milliseconds, with 0.224 milliseconds in Layout. These are separate instrumented runs, not replacements for the untraced 15-pair timing table. Trace overhead and run variation matter. No Paint event occurred inside either synchronous marked interval; that does not mean the visual update was never painted afterward. [3]

Measured Chromium layout passes inside one update BAR

Separate instrumented run per method. Counts are Layout events inside the method’s User Timing markers on the main thread; navigation and later drawing are excluded.

View chart data
Measured Chromium layout passes inside one update
Update patternLayout events (count)
Batched writes1
Interleaved write/read400

The fix is scheduling, not a more powerful selector

A geometry read after an invalidating write can require the browser to bring style and layout up to date synchronously. Doing that in a loop prevents work from being coalesced. The web.dev guidance calls this layout thrashing. The best optimization here did not change a selector, add important or alter a layer. It changed when the program asked the browser for geometry. [20]

batch-layout.js
// Avoid: each read can force pending layout after a write.
for (const tile of tiles) {
  tile.style.width = "40px";
  consume(grid.offsetWidth);
}

// Prefer when only the final grid width is needed.
for (const tile of tiles) {
  tile.style.width = "40px";
}
consume(grid.offsetWidth);

// If every element needs an existing measurement, read first.
const widths = tiles.map((tile) => tile.offsetWidth);
tiles.forEach((tile, index) => {
  tile.style.width = `${widths[index] + 1}px`;
});

These implementations answer different questions if the program truly needs a fresh intermediate grid width after each mutation. In our fixture it does not. Batching is valid because the required result is the final state. Do not delete necessary observations merely to make a benchmark faster. requestAnimationFrame can help align updates with rendering, but putting a read/write/read loop inside it still forces the same dependencies. [20]

Do not rank browser engines from the chart. Firefox and WebKit exposed coarser timing increments here; their one-millisecond batched medians have limited resolution, and one WebKit sample rounded to zero. Versions, build configuration, timer precision and the fixture all matter. The robust result is the within-engine difference and the directly observed Chromium layout count, not a universal speed league table. [3]

Nor are these Core Web Vitals. A long synchronous block can contribute to interaction delay, but this experiment does not establish a field INP, LCP or CLS value. It does not isolate selector-matching complexity or prove that specificity is slow. Those would require different experiments and a different workload. [19] [3]

What exactly passed in the browser lab?

The suite used separate same-origin iframe documents so styles from one test could not accidentally win another test’s cascade. Each case retained its CSS, expected value, observed value and supporting details. It covered layer order, important reversal, inline styles, selector-list differences, nesting, scope, inheritance, parse and computed-value errors, rollback, shorthands, registration, animation, transitions, shadow hosts and resolved widths. [3]

A pass means that this fixture produced the expected observable result in these builds. It is not exhaustive CSS conformance, a compatibility claim for all shipping browser versions, a test of user-origin override UI, or a measurement of assistive technology behavior. The distinction matters most around newer features and APIs. Keep the exact browser version with the result. [3]

Observed results, not a browser support matrix3 rows
Scroll horizontally to see all columns
Observed results, not a browser support matrix
Engine usedUser-agent/build identityCases matchedTyped OM width read
ChromiumHeadlessChrome/159.0.8154.636 / 3650%
FirefoxFirefox/159.036 / 36Unavailable in this build
WebKit automation buildVersion/27.2 Safari/605.1.15 user-agent36 / 3650%

A debugging procedure that works for developers and agents

First identify the element and the longhand property that is wrong. Inspect the actual DOM and state: classes, attributes, pseudo-classes, viewport, container size and shadow boundary. Confirm the relevant stylesheet loaded and parsed. A source file in a repository is not proof that the browser received that version.

Next inspect matched declarations in DevTools. Check whether a rule is inactive because its condition fails, its selector misses or its syntax is invalid. Then compare the earliest differing cascade boundary: origin/importance, context, element-attached style, layer, specificity, scope proximity, source order. If the declarations are on different elements, stop comparing specificity and inspect inheritance instead. [2] [10]

Then inspect value processing. Expand the shorthand into the longhand you care about. Trace var() inputs on the consuming element. Check registered syntax, fallback semantics and computed-value invalidity. Inspect active animations and transitions. Compare the resolved result with box geometry when the symptom is dimensional. A crossed-out declaration and an unexpected pixel are different observations. [14] [17] [15]

Finally change the smallest owned cause and recheck the relevant states. Prefer correcting the layer boundary, removing an accidental shorthand reset or editing the actual token over appending another override. For an agent, record the competing declarations and the first comparison that decides them. “Raised specificity until it looked right” is not an explanation or a reliable repair strategy.

A useful evidence record for a CSS fix6 rows
Scroll horizontally to see all columns
A useful evidence record for a CSS fix
QuestionRecord
What is wrong?Element identity, state, longhand property and expected result
Which declarations compete?Loaded file/rule location, selector, origin, importance and layer
Why does one win?The first differing cascade comparison; do not skip to specificity
What value is exposed?Resolved value, relevant custom properties and active motion
What does the box do?Geometry and rendering trace when performance or layout is the issue
What changed?One owned cause, then the affected responsive and interaction checks

The durable way to use the cascade

Use layers for architectural precedence, low-specificity selectors for adaptable components, scope for bounded matching and proximity, and custom properties for explicit styling inputs. Reserve important for an actual requirement with a known boundary. Read computed or resolved values as outputs, then follow the dependencies when the output is wrong.

The cascade is not a conflict you eventually escape by choosing the right framework. Frameworks can change how styles are produced, named and delivered; the browser still has to resolve the applicable declarations and turn their values into a frame. Understanding that process gives you a reason for the result—and a smaller, safer change when you need a different one.

The accompanying lab archive contains the runnable HTML, CSS and JavaScript, all 36 case results for each tested engine, the initial transition failure, corrected results, raw timing samples and a trace-window summary. Run it from a local HTTP server and keep your own browser/version notes. The numbers above belong to this experiment; the source makes the reasoning inspectable. [3]

Download The Cascade Lab: runnable source and raw results (ZIP)

INDEX

References & Works Cited

20 SOURCES
  1. Håkon Wium Lie (1994-10-10). Cascading HTML style sheets — a proposal.

    https://www.w3.org/People/howcome/p/cascade.html
    Documentation Accessed: 2026-11-27
  2. Håkon Wium Lie and Bert Bos (1996-12-17). Cascading Style Sheets, level 1 — 17 December 1996.

    https://www.w3.org/TR/REC-CSS1-961217.html
    Documentation Accessed: 2026-11-27
  3. Håkon Wium Lie and Bert Bos (1999). A brief history of CSS — chapter 20, Cascading Style Sheets: Designing for the Web, second edition.

    https://www.w3.org/Style/LieBos2e/history/
    Blog article Accessed: 2026-11-27
  4. World Wide Web Consortium (1996-12-17). W3C releases first specification for Web style sheets.

    https://www.w3.org/press-releases/1996/css1-rec/
    Press release Accessed: 2026-11-27
  5. World Wide Web Consortium (1998-5-12). CSS2: Assigning property values, Cascading, and Inheritance.

    https://www.w3.org/TR/1998/REC-CSS2-19980512/cascade.html
    Documentation Accessed: 2026-11-27
  6. World Wide Web Consortium (2011-6-7). Cascading Style Sheets Level 2 Revision 1.

    https://www.w3.org/TR/2011/REC-CSS2-20110607/
    Documentation Accessed: 2026-11-27
  7. Miriam Suzanne (2022-2-21). A Complete Guide to CSS Cascade Layers.

    https://css-tricks.com/css-cascade-layers/
    Blog article Accessed: 2026-11-27
  8. MDN contributors (n.d.). Window: getComputedStyle() method.

    https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
    Documentation Accessed: 2026-11-27
  9. Paul Lewis, web.dev (n.d.). Rendering performance.

    https://web.dev/articles/rendering-performance
    Documentation Accessed: 2026-11-27
  10. Jeremy Wagner, Paul Lewis and Barry Pollard (n.d.). Avoid large, complex layouts and layout thrashing.

    https://web.dev/articles/avoid-large-complex-layouts-and-layout-thrashing
    Documentation Accessed: 2026-11-27