Skip to content

Cascade

James Conway edited this page Nov 19, 2026 · 5 revisions

The CSS module's third part: parsec_css::cascade styles a Parsec document the way a browser cascades, and gives you any element's computed value as getComputedStyle() would. Under it, parsec_css::media evaluates media queries and parsec_css::supports evaluates @supports, both against an environment you hand in rather than a screen. It's all in the parsec-html-css crate, on top of CSS and CSS values, with one new dependency, on Parsec's own HTML parser for the document and its selector engine.

What it doesn't do is layout. A computed value that needs boxes to work out, width: 50% as pixels or grid-template-columns: repeat(auto-fill, …) as tracks, stays as its computed value, which isn't what getComputedStyle() gives for those. Where layout would decide something, you decide it instead: a container's size for @container, and what an @import's URL gives.

On this page: Using it · The cascade · Computed values · @scope · @container · @import · @property · @keyframes and @counter-style · Media queries · @supports · Conformance · What fails, and why · Speed · Fuzzing · Next to Lexbor

Using it

use parsec_css::cascade::{Origin, Styler};
use parsec_css::media::Environment;

let doc = parsec::parse(
    "<style>@media (min-width: 600px) { p { font-size: 2em } } .x { color: red !important }</style>\
     <p class=x style='color: blue'>hi</p>",
    false,
);
let env = Environment { width: 800.0, ..Environment::default() };
let mut styler = Styler::new(env).with_document_styles(&doc);
styler.add("p { margin: 1em 0 }", Origin::User);
let styled = styler.style(&doc);

let p = parsec::css::SelectorList::parse("p").unwrap().select_first(&doc, doc.root()).unwrap();
assert_eq!(styled.get(p, "color").as_deref(), Some("rgb(255, 0, 0)")); // !important beats style=""
assert_eq!(styled.get(p, "font-size").as_deref(), Some("32px"));
assert_eq!(styled.get(p, "margin-top").as_deref(), Some("32px"));
  • Styler::new(env) starts with the HTML Standard's user agent stylesheet (HTML_UA_STYLESHEET, from its rendering section); Styler::bare(env) starts with nothing.
  • add(css, origin) adds a sheet; add_with_media(css, origin, media) adds one that applies only where media matches, as <link media> does; with_document_styles(&doc) adds the document's own <style> elements, their media attributes included.
  • style(&doc) styles every element and gives a Styled; get(element, property) is the computed value, written out. style_element(&doc, el) styles one element and its ancestors only, which is all one element's values need.
  • style_attributes(false) leaves style="" out.
  • fetch(|url| …) gives @imports their sheets; without it they're ignored. container_sizes(|el, computed| …) gives each container's width and height in CSS pixels for @container; a size query on a container it gives no size for is false.
  • at_rules() gives the @keyframes, @counter-style and @property rules in force, one of each name.

The cascade

CSS Cascading and Inheritance Level 5, §6, in that order:

  1. Origin and importance. Normal user agent, user, author; then important author, user, user agent.
  2. Element-attached styles. style="" beats every rule at its origin and importance, layers and specificity included.
  3. Layers. @layer a, b; names them in order, @layer a { } and @layer a.b { } fill them, and @layer { } makes an anonymous one each time. Later layers beat earlier ones, a layer's own rules beat its sublayers', and unlayered rules beat all of them; for !important it's the other way round, so the first layer wins and unlayered loses.
  4. Specificity, per complex selector: a, #b { } is two rules with two specificities, as the spec has it.
  5. Scoping proximity, CSS Cascade 6 §6.6: between two @scoped rules, the one whose root is fewer generations up wins, and a rule with no scope is the farthest of all.
  6. Order of appearance.

Rules nest as CSS Nesting says: .a { & > b { } } is :is(.a) > b, and a nested rule without & is a descendant. @media and @supports apply their rules only when they hold, inside a style rule too. A shorthand is split into its longhands as it's cascaded, so margin then margin-top does what you'd think; with var() in it, each longhand waits for substitution. all sets every property but direction and unicode-bidi.

To keep matching cheap, rules are kept by the id, class, type or attribute their rightmost compound needs, and an element tries only the ones it could match.

Computed values

Each element is computed after its parent, per §4.4:

  • The CSS-wide keywords. inherit, initial, unset; revert rolls back to the origin before, and revert-layer to the layer before, and then the origin before.
  • Inheritance. What isn't declared inherits if the property does (the property table says), and is its initial value if not.
  • Custom properties and var(). An element's custom properties resolve against each other and the parent's (CSS values), and a value with var() is substituted and parsed then. If it doesn't parse, it's invalid at computed-value time, which is unset.
  • Lengths are absolute: em against the element's font size (the parent's in font-size), rem the root's, viewport units the environment's, and container units, with no container, the small viewport's. ex, ch and the like are half an em, the specs' fallback with no font. Angles are in degrees and times in seconds. Math functions are worked out once their lengths are known.
  • Colours are worked out: named and system colours as rgb(), currentcolor as the element's colour, and relative colours and color-mix() computed in their space, as CSS Color 5 has them.
  • Per-property rules, the common ones: font-size keywords, larger and smaller; font-weight's bold, bolder and lighter; line-height lengths; border, outline and column-rule widths, 0 when their style draws nothing; display blockified for the root and for flex and grid items; opacity as a number between 0 and 1; filter functions' percentages, defaults and limits; <position>s as percentages and calc(); gradients' defaults left out.
  • Shorthands write themselves from their longhands, as getComputedStyle() does for the ones whose longhands line up.

@scope

@scope (.card) to (.content) { img { … } } styles the imgs under a .card, but not those in a .content inside it. Without a (start) the root is the parent of the <style> the rule is in (or the document, for a sheet added with add), and inside a style rule it's that rule's element. Inside the rule, a selector without :scope or & is under the root, & is :where(:scope), :scope is the root, and declarations straight in the @scope apply to the root. to (:scope) scopes nothing. Scopes nest, eight deep at most; each element's roots are worked out once, from its parent's, so a deep document with many scoped rules stays linear in its size.

@container

@container card (width > 400px) { … } applies when the element's nearest container named card whose container-type covers the axes the query asks about (size for heights, inline-size or size for widths) is wider than 400px. A container needs a box: one with display: none or contents is passed over. container_sizes says how big each container is, with its computed values to hand, so you can read width and height off them or give sizes from your own layout. A comma-separated list holds if any query does.

The query is a media condition over the size features (width, height, inline-size, block-size, aspect-ratio, orientation, with min-, max- and ranges), three-valued as in media queries, and style() queries on the container's custom properties: style(--theme: dark), style(--accent), ranges, and those joined with not, and and or. Every element is a container for style(). A style() with anything in it that isn't a property's feature is unknown, as browsers have it.

A range compares two or three values, style(--gap > 1em) or style(10px <= --gap < 2em), with the comparisons all one way when there are three. Each value can be a custom property's name, which stands for its value on the container, or any value with var() in it. Every value is then read as a number, percentage, length, angle, time, frequency or resolution and computed on the container, so em is the container's. If one can't be read that way, or two being compared are of different types, the range is false rather than unknown, as CSS Conditional 5 §6.2 says. A unitless zero is a length when the other side is one, so style(0 < 3px) holds.

Lengths in a size query are relative to the container too: em is its font size, and calc(10px + 10em) adds the two once both are pixels.

Container query units

cqw, cqh, cqi, cqb, cqmin and cqmax are worked out at computed-value time. Each one uses the nearest ancestor that's a size container on its axis: size contains both axes, and inline-size contains the container's own inline axis, which is its height if its writing mode is vertical. cqi and cqb follow the writing mode of the element that uses them. So cqi and cqb on one element can come from two different containers, and cqmin and cqmax take the smaller and the larger of those two. With no container on an axis, the unit is the small viewport's, which here is the environment's width or height. Inside a @container prelude, the units are the container's own: (width = 50cqw) compares the container's width with its own nearest container's. The sizes come from container_sizes. If it gives no size for a container, the units look past that container to the next one out.

parsec_css::rules::ContainerQuery parses and evaluates a query on its own, and writes it back as conditionText does.

@import

@import url(theme.css) layer(theme) supports(display: grid) screen; fetches theme.css through your fetch, if supports() holds and the media list matches, and puts its rules in layer theme (layer alone is an anonymous layer of its own). The layer is named even if the fetch gives nothing, as the spec says. Only @imports before any other rule count, after @charset and @layer statements, which name their layers first. scope((.card)) puts the imported rules in that @scope, and scope() in the implicit one. Imports nest sixteen deep, and one styling follows 256 of them at most, so a sheet that imports itself ends.

@property

@property --gap { syntax: '<length>'; inherits: false; initial-value: 4px } registers --gap: a declared value that doesn't match the syntax is invalid at computed-value time and takes the initial value (or the parent's, if it inherits); a value that does is computed, 2em as pixels and red as rgb(255, 0, 0); and an element with nothing declared has the initial value if the property doesn't inherit. The syntax is CSS Properties and Values §5's: *, or type names (<length>, <color>, <length-percentage> and the rest of the fifteen) and keywords, with + and #, joined with |. A missing or invalid syntax is * and inherits is true, as CSSOM has them; an initial value that doesn't match, or depends on the element (1em, var()), makes the rule invalid; and a syntax other than * with no initial value registers nothing. rules::PropertyRule and rules::Syntax give you the parsing on its own.

@keyframes and @counter-style

Parsed, and given back by at_rules(), the last of each name in the cascade's order winning, layers counted: rules::Keyframes has each keyframe's offsets (from, 50%, entry 10%) and declarations, !important ones left out; rules::CounterStyle has each valid descriptor written back in its canonical form (system: fixed 3, symbols: a "b"), and usable() says whether its system has what it needs. Nothing animates and no counter is drawn: those need time and layout.

Media queries

MediaQueryList::parse(&values) reads a <media-query-list> as Media Queries Level 5 has it: media types with not and only; conditions with and, or and not and parentheses; plain features ((min-width: 600px)), boolean ones ((hover)), and ranges, one-sided ((width >= 600px)) and two ((400px < width < 800px)); ratios and math in values. A query that doesn't parse is not all, and the rest of the list stands. to_string() writes it back as mediaText does.

matches(&env) evaluates it against an Environment: the media type, the viewport and the screen in CSS pixels, the resolution, colour depth, the font size em is in, and a value for each discrete feature. Environment::default() is a 1280×720 colour screen at 1dppx that can hover with a fine pointer, light scheme, no preferences. Evaluation is three-valued: a feature nobody knows, or a value it can't take, is unknown, and unknown is false, not or no not.

The features: width, height, aspect-ratio, device-width, device-height, device-aspect-ratio, resolution, color, color-index and monochrome as ranges (with min- and max-), and orientation, scan, grid, update, overflow-block, overflow-inline, color-gamut, dynamic-range, video-dynamic-range, inverted-colors, pointer, any-pointer, hover, any-hover, scripting, prefers-reduced-motion, prefers-reduced-transparency, prefers-reduced-data, prefers-contrast, prefers-color-scheme, forced-colors, display-mode and environment-blending as keywords.

@supports

supports(&values) evaluates a <supports-condition>: not, and, or and parentheses, a declaration (supported when its value parses for its property, through the property table), selector() (when Parsec's selector engine parses it), and font-format() and font-tech() (when they name a format or technology the specs define). Anything else in parentheses is false. supports_text(css) is CSS.supports(conditionText), which also takes a bare declaration, and supports_declaration(property, value) the two-argument form.

Conformance

Three more suites from web-platform-tests, all at the same pinned commit (1a2a0c5) with its licence, all in cargo test and the CI summary.

Suite Data Passed Failed Skipped
Media queries tests/wpt-media, from css/mediaqueries 1,370 0 14
Computed values tests/wpt-computed, from css/*/parsing and css/*/inheritance*, with the files 11,287 754 357
Cascade and at-rules tests/wpt-cascade, from css/css-cascade, css/css-conditional/container-queries, css/css-properties-values-api and css/css-counter-styles/counter-style-at-rule, with the files and what they import 1,198 147 195
wpt media queries: 1370 passed, 0 failed, 14 skipped
  applies: 1052 passed, 0 failed
  parseable: 283 passed, 0 failed
  serialize: 35 passed, 0 failed
wpt computed values: 11287 passed, 754 failed, 357 skipped
  computed: 10835 passed, 728 failed
  inherited: 230 passed, 9 failed
  initial: 222 passed, 17 failed
wpt cascade: 1198 passed, 147 failed, 195 skipped
  css-cascade: 281 passed, 12 failed
  css-conditional: 618 passed, 112 failed
  css-counter-styles: 200 passed, 0 failed
  css-properties-values-api: 99 passed, 23 failed

These tests are JavaScript that asks the browser things, so each has a Node script in crates/parsec-css/scripts that runs the files in a sandbox with no DOM, where what a test asks goes through a probe, and records what the test expects:

  • Media queries (wpt-media-cases.js). Whether a query applies (through a <style media> and the computed style it gives, or matchMedia().matches), whether it parses (whether mediaText comes back not all), and how matchMedia().media writes it. A probe in a test answers yes, and the assertion then says what the test wants. Most of the cases are the Mozilla suite, test_media_queries.html, which changes the viewport between tests; the viewport is recorded with each case. Where it asks outside a test (to find the colour depth or resolution to test around), the probe answers for the environment the runner gives. The 14 skipped probe more than once in a test.
  • Computed values (wpt-computed-cases.js). Every test_computed_value(property, specified, computed), the colour tests' fuzzy_test_computed_color, and inheritance-testcommon.js's assert_inherited, assert_not_inherited and assert_initial. The runner parses the test file itself with Parsec, applies its <style>s and the user agent stylesheet, sets the value on #target as the test does, in an 800×600 viewport as WPT's is, and checks the computed value, and that it computes the same when set again. 12,041 cases from 378 files. The 357 skipped are tests that change the page from script or need a pseudo-element.
  • Cascade and at-rules (wpt-cascade-cases.js). Tests that add <style> elements from script and read a computed style, or read a rule through CSSOM: the additions are recorded, a <template>'s contents put into the page are recorded (the @scope tests are written that way), and an element is found again by the selector the test used, under the element it looked in. A sheet's cssRules.length, a rule's attributes (conditionText, syntax, inherits, initialValue, constructor.name) and whether its cssText has a descriptor in it are probes too, which the runner answers as CSSOM would: invalid rules dropped, the rest written back. The tests' own helper scripts (cq-testcommon.js, counter-style-testcommon.js, the properties-and-values utils.js) run in the sandbox, and promise_tests run one after another, a <style>'s load event firing when it's added. The runner fetches @imports from the files beside the test or from their data: URLs, and gives each container its computed width and height where they're in pixels, which is how the tests size them. 1,975 cases from 129 files; the 195 skipped change the page from script beyond styles and templates (element.style, className), need layout (offsetTop), shadow DOM or CSS.registerProperty.

Each runner has a known-failures.txt; the run fails if anything else fails or a listed case passes. UPDATE_KNOWN_FAILURES=1 cargo test -p parsec-html-css --test wpt_computed (or wpt_media, wpt_cascade) rewrites one, and scripts/fetch-wpt-cascade.sh COMMIT moves all three to another WPT commit.

What fails, and why

The computed values' 754, by what's behind them. #92's canonical forms took 313 off the list, since a computed value is written in the same shortest form:

What Why
Values that need layout getComputedStyle() gives used values for some properties: grid-template-columns and grid-template-rows as track sizes (156 cases), transform-origin and perspective-origin as pixels, width, height and margin percentages. There are no boxes here.
Per-property computed forms not done What a computed value resolves that a specified one keeps: mask and mask-image's URLs, font-synthesis, offset-path and shape-outside shapes with lengths in them, vertical-align's longhands.
Colour corners 121 cases: hue powerlessness at the thresholds browsers use, mixes whose colours are mixes, and color-layers().
Values the parser rejects Everything CSS values rejects can't compute either.

The cascade and at-rule tests' 147. #100 took 57 off the list: 39 style ranges (one more is style(--foo: bar;), now unknown as it should be), 12 container query units in @container preludes, and 6 size queries with calc() mixing px and em or rem:

Cases What Why
31 style() queries Queries on registered properties, on colours, and on values with var(), which need the queried value computed as the property would compute it
27 Shadow DOM Containers and @scope across shadow trees, :host, ::slotted and tree-scoped container names. The tests use declarative shadow roots (<template shadowrootmode>), and Parsec's tree builder doesn't attach them yet: The document tree has no shadow roots
13 Pseudo-elements ::before, ::after, ::marker, ::first-line, ::first-letter and ::backdrop as containers or styled inside one; Styler styles elements, not pseudo-elements
23 @property Animating registered properties, unit cycles through font-size, and initial-values with blocks in them
6 Container query units in animations @keyframes with cqw and the rest, sampled part-way through: there's no animation here
2 An auto-sized container's units container-units-auto.html: the container's height is 0 under size containment, but its width is auto, so the runner can't give its size without layout
19 Containers that layout decides Fragmentation, multicol, grid items, an ancestor with display: none, and containment that doesn't take
7 Unknown features Queries where browsers find a feature unknown that this finds known, or the other way
4 @scope @starting-style in a scope, and @import … scope() with & rules in the imported sheet
6 var() in a size query Substituted against the container
6 revert-rule The tentative keyword
3 Animations @keyframes inside @container, and animated container longhands

Speed

Timed in bench/ (cargo run --release --manifest-path bench/Cargo.toml -- css, at the end of the CSS tables): each of the 13 real pages parsed, then every element's computed values from the user agent stylesheet and the page's own <style> elements, median of five runs, freeing not timed. Most of these pages bring their CSS in by <link>, which isn't fetched, so for them it's the user agent sheet alone; the five with <style> CSS are the ones to look at.

Page Elements <style> CSS ms
reddit-programming 1,280 284 KB 196.1
bbc-news 1,668 71 KB 47.1
nytimes 6,454 43 KB 76.8
wikipedia-population 10,276 32 KB 118.8
wikipedia-html 8,069 21 KB 94.6
whatwg-full 337,200 none 1,972.2
All 13 2,766.3

That's the second of two runs on 18 November 2026, each started with the one-minute load under 2.8; the first was within 1% on the total (2,770.5). It's about 6 µs an element with the user agent sheet alone (the HTML spec, 337,200 elements, in two seconds), and more where a page's own CSS is big: reddit's 284 KB of rules, many of them selectors that can only be tried by matching, cost 150 µs an element. Rules are bucketed by their rightmost id, class, type or attribute, so an element only tries the ones that could match; the selectors that can't be bucketed are the cost.

There's nothing to time against: Lexbor's style module attaches declarations to elements, but doesn't cascade them into computed values, evaluate media queries or inherit.

Fuzzing

The parse fuzz target also parses its input as a media query list and a supports condition, writes the media query list, evaluates both, and cascades the input as an author stylesheet onto a small page, reading a few computed values back. It ran clean for five minutes locally, 236,000 inputs. With #95 it also parses every at-rule as @keyframes, @counter-style, @property, @import, @scope and @container and writes each back, evaluates the container queries, and cascades with every @import fetching the input itself again and every container sized, so imports nest as deep as they're allowed. It ran clean for five minutes three times, 167,521, 148,288 and 133,166 inputs.

Next to Lexbor

Lexbor 3.0.1 Parsec
Stylesheets onto a document Its style module attaches <style> and style="" declarations to elements The cascade in full: origins, layers, specificity, importance, style="", nesting
Media queries Parsed by some at-rules; not evaluated (its roadmap) Parsed, written back and evaluated against an environment you give; all 1,370 WPT cases
@supports Not evaluated Yes
@scope, @container, @import, @property No Yes: scoping proximity, container sizes and style() from you, imports through your fetch, registered properties
@keyframes, @counter-style @font-face-style typed at-rules for a few; neither of these Parsed and given back, the winner of each name
Computed values, inheritance No (discussion #265) Yes, as getComputedStyle() writes them; 11,287 of WPT's 12,041
var() No (lexbor#232) Yes
Layout No No

See also

  • CSS values, for the typed values, colours and custom properties this computes with.
  • CSS, for the syntax parser underneath.
  • Conformance, for every suite Parsec runs.

Clone this wiki locally