Repository navigation
CSS values
parsec_css::values is the CSS module's second part: what a declaration's value means. It knows every property in the CSS specs, 822 of them, and parses a value the way element.style[property] = value does in a browser: against the property's grammar, with its colors, lengths and math functions typed, and written back the way CSSOM writes it. Custom properties resolve against each other and var() substitutes into anything. It sits on top of the syntax parser on CSS, in the same crate, with no new dependencies.
Which declaration wins, media queries, and computed values with inheritance are on Cascade, built on this.
On this page: Using it · The property table · Parsing a value · Numbers, units and math · Colors · Shorthands · Custom properties and var() · Conformance · What fails, and why · Speed · Fuzzing · Next to Lexbor
use parsec_css::values::{expand, parse_value, property};
let p = property("border-top-width").unwrap();
assert_eq!((p.initial, p.inherited), (Some("medium"), Some(false)));
let v = parsec_css::parse_component_values("CALC(1in + 2px) AUTO");
assert_eq!(parse_value("margin", &v).unwrap().to_string(), "calc(98px) auto");
let v = parsec_css::parse_component_values("1px 2px");
let sides: Vec<String> = expand("margin", &v)
.unwrap()
.iter()
.map(|(name, value)| format!("{name}: {value}"))
.collect();
assert_eq!(sides, ["margin-top: 1px", "margin-right: 2px", "margin-bottom: 1px", "margin-left: 2px"]);For a declaration you already parsed, parse_declaration_value(&declaration) does the same with its name and value.
property(name) looks a property up, ignoring ASCII case; properties() gives all of them, sorted by name. Each is a PropertyData:
| Field | What it is |
|---|---|
name |
margin-top |
syntax |
The grammar, in the value definition syntax: <length-percentage> | auto | <anchor-size()>
|
initial |
The initial value as the spec writes it; prose for a shorthand ("see individual properties") |
inherited |
Some(true), Some(false), or None where the spec says something else |
longhands |
For a shorthand, the longhands it sets, in the spec's order |
alias_of |
For a legacy alias like -webkit-box-align, the property it names |
href |
Where the spec defines it |
grammar() gives the grammar parsed, and is_shorthand() says whether it has longhands.
The table is generated, not written by hand. @webref/css is the W3C's own scrape of every CSS spec's property definitions, kept so that every grammar in it parses; its css.json is pinned in crates/parsec-css/data/webref with its version (8.7.9, w3c/webref b6b1622) and MIT licence, and node scripts/properties.js turns it into src/values/generated.rs. Updating to new specs is: replace the JSON, run the script, run the tests.
That's 822 properties: 597 longhands, 161 shorthands and 64 legacy aliases. It's every property in the specs, which is more than any one browser ships; webref doesn't say which ship where, so nothing is filtered. cargo test checks that every grammar parses and that every longhand's initial value is a value of its own grammar; six aren't, and they're listed: four are prose (voice-family: implementation-dependent), and two (fill, text-spacing-trim) use types the data defines only in prose.
The types and functions those grammars refer to come from the same data: 530 types and 172 functions, each parsed once, the first time anything uses it.
parse_value(property, &values) returns a Specified:
| Variant | When |
|---|---|
Value(Vec<Component>) |
The value matched the grammar |
CssWide(CssWide) |
initial, inherit, unset, revert or revert-layer, which every property takes |
Unparsed(Vec<ComponentValue>) |
There's a var() or env() in it, so it can't be checked until substitution: kept as written, as the spec says |
Custom(Vec<ComponentValue>) |
A --custom property: any tokens, kept as written |
or InvalidValue if it doesn't match, or the property isn't one. Display writes it back as CSSOM serializes a specified value.
A Component is one typed value: Keyword (lowercase), Ident (a <custom-ident>, as written), Number { value, integer }, Percentage, Dimension(value, Unit), Math, Color, String, Url, Literal (, and /), Function { name, arguments }, Block and Parens for [ … ] and ( … ), and Tokens for the parts a grammar takes as <declaration-value>.
The matcher reads the grammar as Values 4 §2 writes it: juxtaposition, &&, ||, |, brackets, *, +, ?, {A,B}, #, #{A,B} and !, ranges like <length [0,∞]>, <'property'> references, functions, and literal , and /. It backtracks, so <length>{1,4} or a || b || c find a way through the input if there is one. Commas follow §2.6 exactly: one is left out with the optional terms beside it when everything before it, or after it, or between it and the next comma matched nothing, so linear-gradient(red, blue) matches [ <angle> || … ]? , <color-stop-list>, and linear-gradient(, red, blue) and cursor: url(x) pointer don't. A step budget (200,000 steps a value) keeps a hostile value from taking exponential time; past it, the value is invalid.
What the specs say in prose rather than in the grammar is checked after the match, in values/restrict.rs: the names a <custom-ident> can't be (none as a counter, span and auto as grid lines, will-change and all in will-change, generic families and revert-rule in a family name), counts (steps(0), symbols(numeric "a")), a font feature's four printable letters, grid-template-areas' rectangles, and SVG path data in path(), which values/path.rs parses by SVG 2's grammar and writes back as browsers do (M10,10h80z as M 10 10 h 80 Z). Where webref's grammar is behind its spec, scripts/properties.js writes the spec's in, each with where it comes from: <timeline-range-name>'s keywords, line-clamp, column-width, circle() and ellipse()'s radii, a cursor's image-set(), light-dark() images, a transition's duration that can't be negative.
When it writes a value back, it's in the shortest form CSSOM gives a specified value, which is what WPT checks:
- keywords are lowercase, numbers have six significant figures, units are lowercase, strings are in double quotes and
url()s quoted; - what matched a
||or&&group is written in the grammar's order, which is CSSOM's canonical order:text-decoration-line: blink underlineisunderline blink;hanging-punctuation,word-space-transformandposition-try's flips keep the order they were written in, which matters to them; - in a shorthand's
||group, a longhand at its initial value is left out, and if that's all of it, the first longhand's initial value is what's written:column-rule: currentcolor hidden mediumishidden,text-decoration: solidisnone,columns: auto 3is3; a last/part at its initial value goes too, asfont's/ normal; - a box shorthand leaves out what repeats, at any depth:
margin: 1px 2px 1px 2pxis1px 2px,border-radius: 1px 1px 1px 1px / 1px 1px 2% 1pxis1px / 1px 1px 2%,place-items: center centeriscenter; - types and functions have forms of their own wherever they appear: a position is always two parts or more, across first (
leftisleft center,top leftisleft top);repeat no-repeatisrepeat-x;circle(closest-side)iscircle();polygon(nonzero, …)and around 0corner are left out;scale(250%)isscale(2.5),rotate(0)isrotate(0deg);grayscale(300%)isgrayscale(100%);steps(2, end)issteps(2)andstep-startissteps(1, start);counter(x, decimal)iscounter(x); gradients andcolor-mix()leave out their defaults as CSS Images 4 and Color 5 say; - and 65 properties have rules of their own, in
values/canonical.rs:opacity: 50%is0.5,scale: 100% 100%is1,rotate: 0 1 0 90degisy 90deg,translate: 1px 0pxis1px,counter-reset: xisx 0,grid-area: a / b / a / bisa / b,list-style,maskandline-clampas browsers write them,animation-name: "x"asx,font-family: "New Century Schoolbook"unquoted, anddisplay: inline flexasinline-flex, among the rest.
A keyword the grammar has elsewhere is taken as that keyword, not as a <custom-ident>, where the value can be read that way (Values 4 §4.2): grid-column: span 2 is span and 2, not a line named span, and font-family: Monospace is the generic family monospace.
expand splits shorthands by the longhands their grammar names, by position (sides, a / b), and, for the lists of layers in background, mask, transition and animation, layer by layer, giving each run of values to the longhand that takes it; a longhand that's itself a shorthand (border-width in border) is followed by its own longhands. mask and border reset mask-border and border-image as their specs say.
Every unit in Values 4 and the specs it points to is a Unit: the font-relative ones (em, rem, ex, rex, cap, rcap, ch, rch, ic, ric, lh, rlh), the viewport ones in all four sizes (vw to vmax, then sv*, lv* and dv*), the container query ones (cqw to cqmax), the absolute lengths, angles, times, frequencies, resolutions and fr. Each knows its kind() and, for the absolute ones, its ratio to the canonical unit.
Math::parse(&function) parses a math function: calc(), min(), max(), clamp(), round() with its four strategies, mod(), rem(), sin(), cos(), tan(), asin(), acos(), atan(), atan2(), pow(), sqrt(), hypot(), log(), exp(), abs() and sign(), with e, pi, infinity, -infinity and NaN. + and - need whitespace around them, as the spec says.
The tree is simplified as §10.10 says: sums and products are flattened, values with the same unit added, numbers multiplied in, absolute units made canonical, and a function of values that can be worked out worked out. It's written as §10.12 says, children sorted (numbers, then percentages, then dimensions by unit):
| Written | Serialized |
|---|---|
calc(1px + 2px) |
calc(3px) |
calc(1in) |
calc(96px) |
calc(10px + 5%) |
calc(5% + 10px) |
calc(2 * (1em + 2px)) |
calc(2em + 4px) |
calc(50% + (sign(1em - 10px) * 10%)) |
calc(50% + (10% * sign(1em - 10px))) |
min(1em, 2px) |
min(1em, 2px) |
clamp(1px, 5px, 3px) |
calc(3px) |
atan2(1px, 1px) |
calc(45deg) |
fits(Expect) checks the function's type (§10.9) against where it's used: calc(10% + 1px) is a <length-percentage> but not a <length>, and sin(1px) isn't anything. Where the grammar asks for a number, a length or any other numeric type, a math function of that type matches it; one outside a range like [0,∞] is still valid, since the spec clamps it when it's used.
Nesting is limited to 32 functions or parentheses deep, as browsers limit it; deeper is invalid, not a stack overflow.
Color::parse(&value) reads a <color>: hex in all four lengths, the 148 named colors, transparent, currentcolor, the system colors (deprecated ones too), rgb() and rgba(), hsl() and hsla(), hwb(), lab(), lch(), oklab(), oklch(), and color() in srgb, srgb-linear, display-p3, display-p3-linear, a98-rgb, prophoto-rgb, rec2020, xyz, xyz-d50 and xyz-d65. From CSS Color 5, device-cmyk() and light-dark(). Every channel can be none (outside the legacy comma syntax) or a math function.
It's written as CSS Color 4 §15 and WPT have it:
| Written | Serialized |
|---|---|
#234 |
rgb(34, 51, 68) |
RebeccaPurple |
rebeccapurple (a specified value keeps the name) |
hsl(120 30% 50%) |
rgb(89, 166, 89) |
rgba(2, 3, 4, 50%) |
rgba(2, 3, 4, 0.5) |
hsl(120 30 none / 0.5) |
hsl(120 30% none / 0.5) |
rgb(128 none none) |
color(srgb 0.501961 none none) |
lab(400 0 10/50%) |
lab(100 0 10 / 0.5) (lightness clamped when parsed) |
lch(0 150 -10) |
lch(0 150 350) |
color(xyz 10% 10% 10%) |
color(xyz-d65 0.1 0.1 0.1) |
lab(calc(50 * 3) 0 0) |
lab(calc(150) 0 0) (math kept, unclamped) |
From CSS Color 5, too: relative colors (rgb(from <color> r g calc(b / 2)), in every function and alpha(from …)), with the origin's channel names allowed in the channels and in math, color-mix(), contrast-color() and color-layers(). A relative color is kept as written, its origin serialized, since what r is depends on the origin's computed value; a mix is kept the same way, with its defaults left out.
| Written | Serialized |
|---|---|
rgba(from rgb(20%, 40%, 60%, 80%) r g 25 / 25%) |
rgb(from rgba(51, 102, 153, 0.8) r g 25 / 25%) |
rgb(from rebeccapurple r calc(g * .5 + g * .5) 10) |
rgb(from rebeccapurple r calc((0.5 * g) + (0.5 * g)) 10) |
color-mix(in oklab, 25% red, blue) |
color-mix(red 25%, blue 75%) |
color-mix(in hsl shorter hue, red 50%, blue) |
color-mix(in hsl, red, blue) |
computed() gives a named color as rgb(), as a computed value has it. Converting between spaces, and working out relative colors and mixes, is done as a computed value: Color::absolute() gives any colour's channels, relative colours and mixes worked out, and Cascade has the rest.
expand(shorthand, &values) parses a shorthand's value and returns a value for each of its longhands, in the spec's order. A longhand the value leaves out gets its initial value; a CSS-wide keyword, or a value with var() in it, goes to every longhand. For a longhand, it returns that longhand alone.
The split comes from the grammar. Where a shorthand's grammar refers to its longhands (<'margin-top'>{1,4}, <'row-gap'> <'column-gap'>?, [ <'font-style'> || … ] <'font-size'> …), each part goes to the longhand it matched, with the box rules for one to four sides and "the second, left out, is the first" for pairs like gap. Where it doesn't (border: <line-width> || <line-style> || <color>), each part goes to every longhand that takes it, so border: 1px solid red sets all four widths, styles and colors. Where the grammar is positions rather than longhands, those rules apply too: one to four values over the sides (border-color: red blue), and two separated by / (grid-column: 1 / 3, where a second left out is the first if that's a name). Where none of that works, expand says the value is invalid rather than guess; 92 of WPT's 394 shorthand cases end there today, most of them the repeat() lists of CSS Gaps' column-rule.
CustomProperties holds an element's custom properties as declared: declare("--gap", values). resolve(parent) resolves them all at once:
- every
var()in them is substituted, fallbacks included; - a cycle (
--a: var(--b); --b: var(--a), or through a fallback, or of one property on itself) makes every property in it the guaranteed-invalid value; one that only refers to a cycle takes its fallback, or is invalid itself; -
initialis the guaranteed-invalid value, and what isn't declared comes fromparent, since custom properties inherit.
It finds cycles with Tarjan's algorithm, written without recursion, so a chain of 50,000 properties referring each to the next resolves (there's a test). Substitution can grow a value exponentially, ten var(--a)s of ten var(--b)s and so on; past 100,000 component values a value is invalid, as the spec lets a browser decide, so a hostile stylesheet can't make it allocate without bound.
substitute(&values, &resolved) replaces the var()s in any value, and substitute_value(property, &values, &resolved) does that and parses the result for the property: an error there is "invalid at computed-value time", which the cascade will turn into unset. Tokens substituted stay the tokens they were, so var(--n)px with --n: 1 is a number and an ident, never 1px.
use parsec_css::values::{CustomProperties, substitute_value};
let mut props = CustomProperties::new();
props.declare("--gap", parsec_css::parse_component_values("4px"));
props.declare("--a", parsec_css::parse_component_values("var(--b)"));
props.declare("--b", parsec_css::parse_component_values("var(--a)"));
let resolved = props.resolve(None);
let v = parsec_css::parse_component_values("calc(var(--gap) * 2) var(--a, auto)");
assert_eq!(substitute_value("margin", &v, &resolved).unwrap().to_string(), "calc(8px) auto");env() isn't substituted: no environment is given, so a value with one is invalid after substitution. attr() and registered custom properties (@property) aren't done.
Two suites run in cargo test for values, both pinned with their commit and licence, and in each CI run's conformance summary.
| Suite | Data | Passed | Failed |
|---|---|---|---|
css-parsing-tests' color_* files |
tests/css-parsing-tests, at 203ce36
|
4,803 | 3,258, each checked against a change to CSS Color |
| web-platform-tests' CSS parsing tests |
tests/wpt-values, at 1a2a0c5
|
14,758 | 135, listed |
css-parsing-tests: 5096 passed, 3270 failed, 0 skipped
6 color cases fail because custom color spaces need @color-profile, which isn't parsed yet
4 color cases fail because light-dark() is a pair of colors in the suite, and a color here
2760 color cases fail because the draft now clamps lightness and chroma when parsing them
488 color cases fail because the draft now writes a legacy color with `none` in its own function
wpt css parsing: 14758 passed, 135 failed, 129 skipped
invalid: 5054 passed, 16 failed
shorthand: 321 passed, 73 failed
valid: 9383 passed, 46 failed
(The css-parsing-tests line counts the syntax cases on CSS too: 293 passed and 12 failed of them.)
css-parsing-tests' color files were skipped until now. They're compared as computed colors, which is what the suite records, and with one allowance for precision, which CSS Color 4 leaves to the implementation: legacy rgb() channels are compared to within rounding to integers, and their alpha to three decimals, where the suite keeps six. Every failure is checked by color_difference in the runner against one of four ways CSS Color has moved since the suite was written, and counted under it; one that isn't explained that way fails the run. The big one is clamping: the suite keeps lab(110 0 0) as written, and the current draft, and WPT, clamp it to lab(100 0 0) when it's parsed, so for those 2,760 the runner clamps the suite's answer and checks it then matches.
WPT's CSS parsing tests are the ones every browser runs: css/*/parsing/*.html, which call test_valid_value(property, value, serialized), test_invalid_value(property, value) and test_shorthand_value(shorthand, value, longhands). They're JavaScript, so scripts/wpt-values-cases.js runs each file's scripts in a Node sandbox with no DOM, where those helpers record what the test expects instead of setting a style; the same approach as Netweir's selector tests. Anything else a file does throws there and is counted as skipped, with why: 442 files have nothing static to check, most of them computed-value tests, which are #30's. 777 files give 14,893 cases, in tests/wpt-values/cases.json.
A valid case passes when the value parses for the property, writes back exactly as the test expects (or as one of the forms it allows), and what it wrote parses back to itself, which the test checks too. Colors that WPT compares with a tolerance are compared to within 0.01, as it does, reading 1em as the number 1 and a unit rather than an exponent. An invalid case passes when the value doesn't parse; a shorthand case when each longhand it names comes out as expected, a longhand named by a legacy alias (grid-row-gap) read as the property it aliases.
Every case that fails today is in tests/wpt-values/known-failures.txt, one JSON array a line. The run fails if anything else fails, or if a listed case starts to pass, so the list only shrinks. UPDATE_KNOWN_FAILURES=1 cargo test -p parsec-html-css --test wpt_values rewrites it, and scripts/fetch-wpt-values.sh COMMIT moves the suite to another commit.
To run them with the counts showing:
cargo test -p parsec-html-css -- --nocaptureThe 135 WPT failures, by kind. Of the 508 canonical forms that failed before #92, one is left, and it's a test that disagrees with its neighbours.
| Cases | What | Why |
|---|---|---|
| 73 | Shorthands | CSS Gaps' repeat() lists in column-rule, row-rule and rule (39), which would need each repeat() split across three longhands; rule-inset and its column and row forms (17); grid and grid-template in their areas form (9); animation (3), where webref now makes animation-delay a shorthand and the tests expect animation-range reset; background: border-area (2) and one two-layer background with every part given (1); place-items' safe normal (2) |
| 55 | WPT ahead of the drafts | Values the current editor's drafts don't have, or rule out: safe normal in align-items and justify-items (8), baseline last refused though <baseline-position> is [ first | last ]? && baseline (5), image-orientation without angles (5), font-synthesis: oblique-only (9), text-spacing and text-spacing-trim (10), text-autospace-size (4), quotes: match-parent (2, the draft has bikeshed-this), light-dark() in cursor (4), scroll-marker-group in a fixed order (2), and one each of opacity: auto, ruby-overhang: none, scroll-snap-stop: before, text-emphasis-position: auto, font-palette: -- and mask: margin-box
|
| 6 | Legacy quirks |
-webkit-perspective: 1000 and perspective(1000) taking a unitless length (4), and CSS 2's clip: rect(1px, 2px, 3px, 4px) with commas (2) |
| 1 | A canonical form |
image-resolution: snap -8dpcm from-image is expected as written, where every other image-resolution case expects the grammar's order |
Nothing in that list is a crash, a hang or a case the runner skips; every one is a case it ran and got a different answer for.
Timed in bench/, which also times the syntax parser (see CSS and Benchmarks): the same ten real stylesheets, parsed with parse_stylesheet_deep and then every declaration's value parsed for its property, against Lexbor's lxb_css_stylesheet_parse, which types the values of the 105 properties it knows as it parses.
| All ten, MB/s | Parsec | Lexbor 3.0.1 | Parsec vs Lexbor |
|---|---|---|---|
| Parse, every value typed | 145 | 114 | 1.26× |
That's the second of two runs on 19 November 2026, each started with the one-minute load under 2.1; the first gave 143 to 115, 1.24 times. It's 33,134 declaration values, every one typed for its property (21 fewer than before #92, the ones its prose restrictions now refuse). Parsec is ahead on every sheet in both runs, from 1.04 times Lexbor's speed on the New York Times' <style> elements, where most declarations are short, to 1.9 times on Font Awesome. Before #92 the short-declaration sheets were the slow ones, 0.70 times.
It isn't quite the same work. Lexbor types the 105 properties it knows and keeps the rest as text; Parsec types all 822, custom properties kept as tokens, so where a sheet uses properties Lexbor doesn't know, Parsec is doing more. Lexbor's parse also reads every selector, which Parsec's doesn't.
What made the short sheets fast, found with sample, in the order it mattered:
- A keyword alone,
display: none, is most declarations. Each property's keywords are parsed the long way once, the first time the property is seen, and after that a lone keyword is a table lookup; an identifier that's no keyword of a property that takes no names is refused without the matcher. - A value of one token,
1pxor#fff, is matched against the grammar's plain alternatives directly, through||groups, repeats and longhand references, without the backtracking matcher. - Each type and longhand reference knows what kinds of token its grammar can start with, so
background: #fffdoesn't try<position>and<image>at#fff. - The canonical forms work on the match as it lies for the common shapes, alternatives side by side and longhands of values, and give it back untouched when nothing changes; only the rest builds a tree.
font-familyhas a matcher of its own, since a long list of names took the backtracking matcher a while. - Property names are looked up in an open-addressed table hashed on their first and last eight bytes.
The parse fuzz target in crates/parsec-css/fuzz now also types every declaration's value for its property, writes it, parses what it wrote, splits every shorthand, and resolves the custom properties of whatever it generated against each other, then substitutes them. It ran clean for five minutes twice locally, 1.1 million inputs and then 600,000 on the final code. With #92 it also parses every declaration's value as the properties with canonical forms and shorthands of their own (font, background, mask, grid, animation, transition, clip-path, offset, grid-template-areas and others) and splits them, and ran clean for five minutes twice, 276,444 and 233,969 inputs.
cd crates/parsec-css
cargo +nightly fuzz run parse -- -max_len=4096| Lexbor 3.0.1 | Parsec | |
|---|---|---|
| Typed properties | 105 | All 822 in the specs, from their grammars |
| Where the property list comes from | Hand-written | Generated from w3c/webref's scrape of the specs |
var() and custom properties |
No (lexbor#232) | Yes: resolved, cycles found, substituted anywhere |
| Math functions | No: no calc()
|
calc() and all of Values 4's, simplified |
| CSS Color 4 and 5 | Color 4's functions, rgb() to color()
|
All of Color 4, with none and math in any channel; from Color 5, relative colors, color-mix(), contrast-color(), light-dark(), device-cmyk()
|
| Shorthands into longhands | For the ones it knows | From the grammar, where it shows how |
| Outside suite | No | css-parsing-tests' colors and WPT's parsing tests, counts published |
| Cascade, media queries, computed values | No | Yes (Cascade) |
- CSS, for the syntax parser this sits on.
- Conformance, for every suite Parsec runs.
- Benchmarks, for the method behind the speed numbers.
Parsec is Apache-2.0 and not yet released; these pages describe main. Found something wrong here? Open an issue or ask in Discussions.
Repository · Issues · Discussions · Roadmap · Security policy · Licence