`, so `calc(1px + 2px)` computes to `3px`. It doesn’t inherit, so the `` inside the card gets the initial `8px`, and `red` doesn’t fit the syntax, so `.bad` gets `8px` too.
- With the font metrics, `20ch` at 16px is 20 × 0.55 × 16 = `176px`. Without them, `ch` is estimated at half an em.
- `InvalidDeclarations` lists the declarations that won the cascade but have no value at computed-value time, with their source. `ComputedStyle.InvalidDeclarations` does the same for one element.
## Where next
- [Overview](https://recursiveai.org/onehtml/go/docs/overview/): the README, with the quick start and the packages.
- [Changelog](https://recursiveai.org/onehtml/go/docs/changelog/): what changed in 1.1.0 and 1.1.1.
- [Package documentation](https://pkg.go.dev/recursiveai.org/go/onehtml) on pkg.go.dev, with an example for each feature.
# onehtml
**A pure-Go HTML and CSS library that parses HTML exactly as a browser does, matches Selectors Level 4, computes the CSS cascade, edits a page without disturbing a byte the edit didn't touch, and builds the accessibility tree a browser gives screen readers.** It also checks pages against every WCAG level, from the standard library alone.
## Why onehtml
- **Browser-exact parsing.** The WHATWG tokenizer and tree builder in full, fragments and parse errors included, with the Encoding Standard's detection and decoders. Every node and attribute knows its byte range in the original input.
- **Selectors and cascade.** Selectors Level 4 compiled once and matched without recursion; origins, layers, `@scope`, nesting, `@media`, `var()` and `calc()`, with computed values serialized as `getComputedStyle` gives them. No layout, no painting.
- **Lossless editing.** `Rewrite` splices edits into the original bytes and verifies the result by parsing it again; with no edits the output is byte-identical to the input.
- **Accessibility.** The accessibility tree (WAI-ARIA 1.2, HTML-AAM, Accessible Name and Description 1.2), a reading view and navigation lists, and a checker for WCAG 2.0, 2.1 and 2.2 with suggested fixes and JSON, axe-compatible JSON, SARIF and EARL exports.
- **Safe on hostile input.** No panic and no hang on any bytes; limits are checked before the work they guard, and nothing recurses on input depth.
- **Never fetches, never executes.** The library opens no files and makes no network requests; linked stylesheets come from the caller and scripts are inert text. Standard library only, no cgo, no `unsafe`.
## Install
```
go get recursiveai.org/go/onehtml
```
Go 1.24 or newer.
## Quick start
```go
doc, err := onehtml.Parse(strings.NewReader(`
Home `))
if err != nil {
log.Fatal(err)
}
links, err := doc.Select("nav a[href^='https://']")
if err != nil {
log.Fatal(err)
}
styles := doc.Style()
for _, a := range links {
href, _ := a.Get("href")
fmt.Println(a.TextContent(), href, styles.ComputedStyle(a).Get("color"))
}
res := onehtml.Rewrite(doc, []onehtml.Edit{onehtml.SetAttribute(links[0], "rel", "noopener")})
if !res.Applied() {
log.Fatal(res.Reasons)
}
fmt.Println(string(res.Document)) // the original bytes, changed only at the edit
```
The same example runs as `Example_quickStart` in the package documentation.
## Where to go
- [`onehtml`](https://pkg.go.dev/recursiveai.org/go/onehtml): parser, DOM, selectors, cascade and editing, with an `Example` for each.
- [`onehtml/accessibility`](https://pkg.go.dev/recursiveai.org/go/onehtml/accessibility): `accessibility.Tree(doc)`, the reading view and navigation lists.
- [`onehtml/accessibility/aria`](https://pkg.go.dev/recursiveai.org/go/onehtml/accessibility/aria): the WAI-ARIA roles, states and properties with their characteristics.
- [`onehtml/accessibility/validation`](https://pkg.go.dev/recursiveai.org/go/onehtml/accessibility/validation): `validation.Check(doc)`, profiles, rules and exports.
- [Conformance](https://recursiveai.org/onehtml/go/docs/conformance/): results against the onehtml conformance kit.
- [Performance](https://recursiveai.org/onehtml/go/docs/performance/): parse and select against x/net/html and cascadia, and floors for the rest.
- [Changelog](https://recursiveai.org/onehtml/go/docs/changelog/) and [security policy](https://github.com/recursive-ai-oss/onehtml-go/blob/b6b36a3de36130cf715d83198af600c71d30c3f2/SECURITY.md).
## Licence
Licensed under either of MIT or Apache-2.0 at your option (`LICENSE-MIT`, `LICENSE-APACHE`). Third-party data is listed in `THIRD-PARTY-NOTICES.md`. Copyright Recursive AI, LLC.
# Conformance
The library is checked against the onehtml conformance kit, a language-neutral
suite of cases taken from the specifications' own test suites (html5lib-tests,
WHATWG and CSS working group tests, WPT, W3C ACT rules, axe-core outcomes,
Chrome accessibility captures) and our own. Results of this library through the
kit's adapter, with the C# onehtml library for comparison. A case the library
does not follow is a recorded deviation with its reason; "unsupported" means the
case needs something the library by design does not do (running script, layout,
a rendered page).
| Suite | Cases | Pass | Partial | Deviation | Unsupported | Fail | C# library: pass |
|---|---:|---:|---:|---:|---:|---:|---:|
| a11y-export | 1553 | 1553 | 0 | 0 | 0 | 0 | 1543 |
| a11y-tree | 3796 | 3734 | 0 | 42 | 20 | 0 | 3409 |
| aria-taxonomy | 217 | 217 | 0 | 0 | 0 | 0 | 150 |
| cascade | 1567 | 1544 | 0 | 3 | 20 | 0 | 1299 |
| catalogue | 461 | 448 | 0 | 0 | 13 | 0 | 446 |
| check | 121 | 119 | 0 | 2 | 0 | 0 | 119 |
| css-condition | 210 | 210 | 0 | 0 | 0 | 0 | 209 |
| css-keyframes | 142 | 142 | 0 | 0 | 0 | 0 | 141 |
| css-syntax | 543 | 543 | 0 | 0 | 0 | 0 | 542 |
| css-update | 124 | 124 | 0 | 0 | 0 | 0 | 123 |
| css-value | 1793 | 1790 | 0 | 3 | 0 | 0 | 1784 |
| dom | 367 | 367 | 0 | 0 | 0 | 0 | 366 |
| edit | 558 | 558 | 0 | 0 | 0 | 0 | 550 |
| encoding | 2129 | 2129 | 0 | 0 | 0 | 0 | 1121 |
| export | 87 | 87 | 0 | 0 | 0 | 0 | 86 |
| mutate | 182 | 180 | 0 | 2 | 0 | 0 | 179 |
| navigation | 142 | 142 | 0 | 0 | 0 | 0 | 125 |
| parse | 11322 | 11315 | 0 | 1 | 6 | 0 | 11316 |
| reading-view | 62 | 62 | 0 | 0 | 0 | 0 | 59 |
| rendered-facts | 91 | 91 | 0 | 0 | 0 | 0 | 90 |
| select | 2184 | 2180 | 0 | 0 | 4 | 0 | 2167 |
| serialize | 103 | 103 | 0 | 0 | 0 | 0 | 103 |
| source-map | 60 | 60 | 0 | 0 | 0 | 0 | 59 |
| validate | 1220 | 746 | 227 | 32 | 215 | 0 | 713 |
| **total** | **29034** | **28444** | **227** | **85** | **278** | **0** | **26699** |
No case fails. A *partial* validate case is one where the library reports
"cannot tell" and the expected answer is a verdict (ACT Rules Format 1.1,
section 4.14). Unsupported parse and a11y-tree cases run script. Unsupported cascade
cases need layout or container-query sizes. Unsupported select cases use the
column combinator, which matches only with table layout. Unsupported validate cases are for
rules the library does not implement or that need a rendered page, script,
frames or several pages; the catalogue rows for those rules are unsupported too.
# Performance
One machine, one day, indicative of relative speed rather than a promise: AMD
Ryzen 9 7950X3D (16 cores, 32 threads), Linux 7.0, Go 1.26.8, 2026-12-01, run
alone on the machine (load average 1.3 before, 1.0 to 2.1 during, 1.6 after),
GOMAXPROCS 32. Each figure is the median of three runs of `go test -bench
-benchmem -count 3`. The corpus is six generated pages in `bench/testdata`
([`bench/README.md`](https://github.com/recursive-ai-oss/onehtml-go/blob/b6b36a3de36130cf715d83198af600c71d30c3f2/bench/README.md)). Before any row counts, a test builds both libraries' trees
(or match lists) for every page and requires them to be identical; they are.
**Parse**, `ParseBytes` against x/net/html (v0.38.0, the faster of the two
versions measured; v0.63.0 is slower still), scripting off in both:
| Page | Size | onehtml MB/s | x/net/html MB/s | Speed-up | onehtml B/op, allocs | x/net/html B/op, allocs |
|---|---:|---:|---:|---:|---:|---:|
| article, small | 16 KB | 156 | 102 | 1.5x | 121 KB, 80 | 157 KB, 1,910 |
| article, medium | 165 KB | 147 | 83 | 1.8x | 1.29 MB, 372 | 1.77 MB, 22,196 |
| article, large | 978 KB | 164 | 85 | 1.9x | 8.6 MB, 1,889 | 10.6 MB, 132,446 |
| product listing | 192 KB | 178 | 109 | 1.6x | 1.80 MB, 78 | 1.62 MB, 25,482 |
| reference page | 165 KB | 145 | 92 | 1.6x | 1.17 MB, 526 | 1.70 MB, 19,821 |
| legacy markup | 224 KB | 104 | 92 | 1.1x | 2.16 MB, 703 | 2.35 MB, 29,426 |
onehtml also keeps the original bytes, the byte range of every node and
attribute, and the parse errors, which x/net/html does not.
**Select**, twenty typical selectors (types, ids, classes, attributes,
combinators, `:nth-child`, `:not`, `:has`), compiled and matched, against
cascadia v1.3.3 on x/net/html trees:
| Page | Compile and match | | Match only | |
|---|---:|---:|---:|---:|
| | onehtml | cascadia | onehtml | cascadia |
| article, medium | 1.35 ms | 2.18 ms | 1.39 ms | 2.16 ms |
| product listing | 0.61 ms | 0.99 ms | 0.64 ms | 0.98 ms |
| reference page | 1.48 ms | 2.33 ms | 1.51 ms | 2.34 ms |
One selector at a time, onehtml is faster on seventeen of twenty and level on
two (`#s17`, `.sec`); `section:has(table)` is 20% slower.
**Rows without a Go competitor**, against floors, single goroutine, on the
medium article page (6,330 elements) unless stated:
| Row | Result | Floor |
|---|---:|---:|
| Cascade: style every element (sheets parsed, three properties read each) | 609,000 elements/s | 300,000 |
| Accessibility tree, `accessibility.Tree` (includes the cascade) | 251,000 elements/s | 50,000 |
| Full check, `validation.Check`, every rule | 76,000 elements/s | 25,000 |
| `Rewrite` of three edits, verified by re-parsing | 70 MB/s (65 MB/s on the 978 KB page) | 20 MB/s |
| `Restyle` after a one-class edit, 7,005-element page | 13 µs (a full restyle: 9.4 ms) | 1 ms |
# Changelog
All notable changes to this library are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project
follows [Semantic Versioning](https://semver.org/).
## [1.1.1] - 2026-12-03
### Added
- `ComputedStyle.SpecifiedDisplay`: the element's `display` as declared, in the
short form `Get` uses, before blockification. A float, an absolutely
positioned element, the root element and a flex or grid item compute to a
block-level `display` (CSS Display 3 section 2.7), so `Get("display")` on a
float declared `inline-flex` reads `flex`; `SpecifiedDisplay` still reads
`inline-flex`, which tells a caller the inner display type.
### Fixed
- `steps()` keeps `jump-start`, `jump-none` and `jump-both` as written when
serialized (`steps(2, jump-start)`, no longer `steps(2, start)`); `jump-end`
and `end` still read as `steps(2)`.
- `object-position` takes a unitless `0` as the offset in its three- and
four-value forms (`top 0 right 1px` is `calc(100% - 1px) 0px`, no longer
refused and reset to `50% 50%`).
- `background-size` computes as browsers report it: a single value is the value
and `auto` (`10px` is `10px auto`), two `auto`s are `auto`, and lengths are in px
(`1em` is `16px auto`). A negative or malformed size is invalid.
- The `background-*` longhand lists (`background-position-x` and `-y`, `-size`,
`-repeat`, `-clip`, `-origin`, `-attachment`, `-blend-mode`) read back as long
as the `background-image` list: a longer list is cut, and a shorter one repeats
from its start (`background-position: left, right` with one image reads `0%`
for `background-position-x`).
### Notes
- The initial `font-family` stays `serif`. Browsers take it from the platform's
default font settings, so it is not fixed by a standard; callers that need
another default set `font-family` on the root.
## [1.1.0] - 2026-12-03
### Added
- `Styles.Registrations` and `PropertyRegistration`: the document's `@property`
rules (CSS Properties and Values API 1). A registered custom property now takes
its initial value when nothing sets it, does not inherit when `inherits` is
false, and has a value that does not match its syntax treated as unset; a
matching value is computed to its canonical form (`calc(1px + 2px)` is `3px`).
`ResolveAnimations` reports a registered custom property that a keyframe sets,
so a caller can interpolate it by its syntax.
- `font` takes the system font keywords (`caption`, `icon`, `menu`,
`message-box`, `small-caption`, `status-bar`), as Chrome reports them on Linux:
a 16px Arial in the normal style and weight.
- The `table` element's `border` attribute sets the four border widths (1px when
the value does not parse).
- `WithFontMetrics`, `FontQuery`, `FontMetrics` and `FontMetricsFunc`: the caller
measures the primary font, and the `ex`, `ch`, `cap` and `ic` units (and the
root-relative `rex`, `rch`, `rcap` and `ric`) take its x-height, zero advance,
cap height and ideograph advance. Without it, or for a measurement the
function leaves at zero, the estimates stay (half an em, 0.7 em, one em).
`font-size` in `ex` is relative to the parent's font.
- `ComputedStyle.InvalidDeclarations` and `Styles.InvalidDeclarations`, with
`InvalidDeclaration`: the declarations that won the cascade but are invalid at
computed-value time (a `var()` that does not fit the property, a shorthand
that does not expand after substitution, a custom property that refers to
nothing or does not fit its registered syntax), with their source.
### Changed
- Several computed values now read back in the forms browsers report, so code
that compared serialized values from 1.0.0 sees new strings: multi-word
`font-family` names are quoted, `font-stretch` is a percentage, a numeric
`line-height` reads as px through `Get` (descendants still inherit the
number), animation times are in seconds, `object-position` and
`background-position-x`/`-y` keywords become percentages, and px lengths are
written with six significant digits. Details under Fixed.
### Fixed
- Media features with a length now match in `vw`, `vh`, `vmin`, `vmax` (and the
small, large and dynamic forms) and with `calc()`, `min()`, `max()` and
`clamp()`, including on the left of a range: `(min-width: 50vw)`,
`(min-width: calc(400px + 400px))`.
- `width: calc(50% - 10px)` no longer drops the length term of a sum with a
percentage in a non-negative property.
- The default style sheet no longer sets `unicode-bidi: bidi-override` on every
element: that block applies to ISO-8859-8 documents only. Block elements are `isolate`
and `bdo` is `isolate-override`, as the HTML Standard's rules say.
- The default style sheet's table rules apply "only if border is not equivalent
to zero": cells of `table[border=0]` no longer get a 1px inset border.
- Medium `monospace` is 13px: a font family list that is the generic `monospace`
alone uses the fixed default size (`pre`, `code`, `kbd`, `samp`, `tt`), with the
keyword scale of that size, and `em`, `larger`, `smaller` and inheritance
under a parent that is not monospace start from the parent's size scaled to
it. `ui-monospace`, named families and lists with other families keep 16px.
- `columns`, `grid-area`, `grid-row` and `grid-column` set their longhands.
`place-content`, `place-items` and `place-self` keep `safe` and `unsafe`.
`font-variant` and `font-synthesis` are expanded, and `font` resets the
`font-variant-*` longhands instead of inheriting them. `column-width` has the
initial value `auto`.
- `var()` in `padding-inline`, `padding-block`, `margin-inline`, `margin-block`,
`inset-inline`, `inset-block` and the `border-inline-*` and `border-block-*`
shorthands now substitutes into the physical longhands.
- A quoted `url('...')` in the `background` shorthand (a data: URL included)
no longer makes `background-image` compute to `none`.
- `animation-delay` reads back the delay list, also when set through the
`animation` shorthand.
- In `ResolveAnimations`, `box-shadow` is one animated property (not its
`box-shadow-*` longhands) and `font-stretch` keeps that name (not `font-width`).
- The default style sheet is regenerated from the current HTML Standard text.
- `word-spacing` takes a percentage and keeps it in the computed value.
- `border-*-width: inherit` takes the width the parent specified, not the 0 the
parent reads when it has no border style (the child's own style still decides
whether the width applies); with nothing specified above it is `medium`, 3px.
- `align-items` and `justify-items` refuse `anchor-center` (`align-self` and
`justify-self` keep it); `page` takes an identifier and refuses a string;
`text-transform` takes `none`, `capitalize`, `uppercase` and `lowercase`
alone, so `full-width` and `full-size-kana` are invalid, as in Chrome 156.
- An unquoted `font-family` name of several words that starts with a generic
family or a CSS-wide keyword (`serif x`) is invalid, and the declaration is
dropped; `x serif` is still a family name.
- Easing functions serialize as browsers do: `steps(4, end)` is `steps(4)`,
`step-start` is `steps(1, start)`, `step-end` is `steps(1)`, and `linear()`
lists every stop with its input (`linear(0 0%, 0.5 50%, 1 100%)`; a stop with
two inputs becomes two stops).
- `object-position` computes as a position: keywords become percentages, an
offset from the right or bottom edge becomes `calc(100% - 10px)`, lengths are
in px, and a `calc()` sum puts the percentage first.
- `text-align` takes `-webkit-left`, `-webkit-center` and `-webkit-right`; the
default sheet makes `center` and `caption` `-webkit-center`, and `th` centred
unless its parent aligns text some other way. The engine keyword
`-internal-center` stands for that last rule and is accepted from any source.
- `text-indent` takes `hanging` and `each-line`, in either order, and computes
them after the length.
- The color scheme of an element decides its system colors and `light-dark()`:
`color-scheme` is read (`normal` is light; `dark` is dark; `light dark` follows
the host's preference; `only` is kept and serialized last). An element without
`color-scheme` stays light under a dark host, as Chrome does. The initial
`color` follows the scheme of the root element.
- The system colors have Chrome's values (`ButtonBorder` black, `Highlight`
`rgba(0, 65, 198, 0.8)`, `SelectedItem` `#1967d2`, `GrayText` gray), and the
deprecated system colors compute as CSS Color 4 section 6.3 maps them
(`Menu`, `Window`, `InfoBackground`, `Background` are `Canvas`; `ThreeDFace`
and `ButtonHighlight` are `ButtonFace`; `ActiveBorder` and `WindowFrame` are
`ButtonBorder`; `WindowText` is `CanvasText`), in the light and dark scheme.
- The default style sheet's `table[border]` rules read the attribute as an
integer: `border=05` is a border of 5, `border=" 0"` and `border=0px` are
none. Their specificity is that of `table[border]`, so `table[frame]` rules
after them win again.
- `font-family` prints a family name that is more than one word, or that needs
escaping, as a quoted string (`"Open Sans", fantasy`, `"Times New Roman"`),
as browsers do; a single identifier stays bare, also when it was quoted.
- `font-stretch` computes to a percentage (`condensed` is `75%`, `normal` is
`100%`), also through the `font` shorthand.
- A numeric `line-height` reads as the length it multiplies out to under the
element's font size (`1.5` at 16px is `24px`), also through the `font`
shorthand; descendants still inherit the number.
- `animation-duration` with no duration computes to `0s` for an animation on
the document timeline (it stays `auto` with a scroll, view or `none`
timeline), and `animation-delay` is written in seconds (`100ms` is `0.1s`).
- `background-position-x` and `-y` compute as positions: keywords are
percentages, `0` is `0px`, an offset from the right or bottom edge is
`calc(100% - 10px)`, and a sum puts the percentage first.
- Registered custom properties compute `` to `deg`, `` to `s` and
`` to `dppx`, and resolve font-relative lengths against the
element's own font size.
- Lengths in px are written with six significant digits, as browsers do
(`13.3333px`, `37.7953px`).
- The default style sheet gives text inputs `1px 2px` padding, a 2px inset border
and the text cursor, buttons `1px 6px` padding and the default cursor,
`textarea` the monospace font and `resize: both`, `label` the default cursor,
and `meter` and `progress` `display: inline-block`.
## [1.0.0] - 2026-12-02
First release.
### Added
- `onehtml/encoding`: the Encoding Standard as a package of its own. `Lookup`
by label, `All`, `FromContentType`; `Encoding.Decode` (the standard's
"decode" with error count, byte order mark handling and an `OffsetMap` between
text and byte offsets) and `Encoding.Encode` (the "html" error mode);
streaming `Decoder` and `Encoder` with `Bytes`, `String`, `Reader` and
`Writer`, correct on any chunk boundary.
- `onehtml`: the WHATWG HTML parser (tokenizer, tree construction in full,
fragments, foreign content, templates, parse errors, the Encoding Standard's
detection and decoders), a read-only DOM in a flat arena with value
handles, serialization, and iterator-based traversal.
- `onehtml/css`: the CSS Syntax tokenizer and parser as a public syntax tree
(`ParseStylesheet`, `ParseBlockContents`, `ParseDeclarations`, `ParseRule`,
`ParseDeclaration`, `ParseValue`, `ParseValues`, `ParseAnPlusB`) with exact
byte ranges for every token, comment, rule and declaration, typed views of
`@import`, `@layer`, `@namespace`, `@container` and `@charset`, canonical
serialization (`SerializeIdent`, `SerializeString`, `ComponentValues.String`),
and parse limits (`WithMaxInput`, `WithMaxTokens`, `WithMaxNesting`).
- `onehtml/css`: media query lists (`ParseMediaQueries`: canonical text, per-query
facts, evaluation against an `Environment`) and `@supports` conditions
(`ParseSupports`, `DeclarationSupported`, `WithSelectorSupport`).
- `WithSheetEnvironmentCharset`: the encoding of the linking document as the last
resort when decoding a stylesheet's bytes.
- Selectors Level 4 (`CompileSelector`, `Select`, `Matches`, `Closest`, `:has()`,
`:is()`, `:where()`, `:nth-child(… of S)` and the rest), with limits on
selector size and complexity.
- The CSS cascade: CSS Syntax 3 parsing, `@media`, `@supports`, `@layer`,
`@scope`, nesting, custom properties with `var()`, `calc()`, Color 4/5, the
user-agent sheet from the HTML rendering section, and computed values
serialized as `getComputedStyle` gives them. Linked sheets are supplied by
the caller; the library never fetches.
- A mutable layer: immutable snapshots, `Editor`, `Document.Apply`, change sets,
and `Styles.Restyle`, which follows an edit incrementally.
- Lossless editing: `Rewrite` splices only the edited byte ranges into the
original document and verifies the result by parsing it again; the family
edit-file format (`ReadEditFile`, `Replay`); `Stylesheet` for `Hi
`
doc, err := onehtml.ParseBytes([]byte(html))
if err != nil {
panic(err)
}
note := doc.ElementByID("note")
if !note.Valid() {
panic("#note not found")
}
styles := doc.Style()
value := styles.ComputedStyle(note)
fmt.Println(value.Get("margin-left"))
}
```
The default viewport is 1,280 CSS pixels wide, so `min-width: 800px` matches. The media rule sets the margin to `1em`, which resolves to `20px`.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/compute-css-style-without-browser/compute-css-style-without-browser.zip) and `go run .`.
`go run .` prints:
```text
20px
```
## Variations
Use a narrower viewport to see the value when the media query no longer matches. Add this inside `main`; it prints `40px`.
```go
ctx := onehtml.StyleContext{
ViewportWidth: 500,
}
narrow := styles.WithContext(ctx)
value = narrow.ComputedStyle(note)
fmt.Println(value.Get("margin-left"))
```
## Related recipes
- [Check HTML for WCAG 2.2 AA and export SARIF in Go](https://recursiveai.org/onehtml/go/cookbook/check-wcag-22-aa-and-export-sarif/)
- [Parse an HTML fragment with element context in Go](https://recursiveai.org/onehtml/go/cookbook/parse-html-fragment-in-context/)
## The short answer
Parse the HTML, call `doc.Style()`, then select an element and read a property with `styles.ComputedStyle(node).Get(name)`. Include the stylesheets and viewport you want the cascade to use. This computes CSS values without starting a browser; it does not measure boxes or run scripts.
## How do I get computed CSS styles for a given element?
Start with the element’s parsed `Node`, not just a tag name. Two paragraphs can match different rules, and values can depend on a parent. For instance, the sample’s `.note` has no `font-size` of its own. It inherits `20px` from `body`, so its `2em` margin resolves to `40px` when the media query does not match. With the example’s initial style context, the media rule wins and `1em` resolves to `20px`. Reading the `style` attribute alone would miss both rules.
If your page has linked CSS, supply the sheet text with `WithStylesheets`, keyed by absolute URL. For relative links, supply the page URL with `WithBaseURL`. The library [never fetches stylesheets](https://recursiveai.org/onehtml/go/docs/overview/). Check `styles.Diagnostics()` for missing sheets before treating the values as representative of the original page. When comparing results from several pages, use the same viewport and the same sheet inputs, or differences in those inputs can change which rules win.
## Can I get the actual pixel width from a computed style?
A value such as the sample’s `2em` can be converted to pixels from the element’s font size. A pixel width that depends on layout is a different question. For example, knowing that an element has `width: 50%` does not tell you how wide its containing block ended up after the page was laid out. The library does not perform that layout step. In browsers, [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle#description) can expose a used value for properties that depend on layout, so a browser value is not always the right comparison for this recipe.
The same distinction applies to scripts. You can inspect styles for the HTML you supply; a script that adds a class or a `
`
doc, err := onehtml.Parse(strings.NewReader(html))
if err != nil {
log.Fatal(err)
}
styles := doc.Style()
for _, rule := range styles.Registrations() {
fmt.Println(rule.Name, rule.Syntax,
rule.InitialValue, rule.Inherits)
}
outer := doc.ElementByID("outer")
inner := doc.ElementByID("inner")
fmt.Println("outer:", styles.ComputedStyle(outer).Get("--gap"))
style := styles.ComputedStyle(inner)
fmt.Println("inner:", style.Get("--gap"), style.Get("margin-left"))
}
```
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/register-css-custom-properties/register-css-custom-properties.zip) and `go run .`.
```text
--gap 4px false
outer: 12px
inner: 4px 4px
```
The rule is printed as name, syntax, initial value, and inheritance flag. The child uses `4px`, not the parent’s `12px`. If an `@property` rule is invalid, it is omitted from `Registrations()` rather than returned with partial descriptors.
## Variations
Set `inherits: true` to let the child receive the parent’s `12px`. Replace the registration in the HTML with:
```css
@property --gap {
syntax: "";
inherits: true;
initial-value: 4px;
}
```
The last output line becomes `inner: 12px 12px`.
## Related recipes
- [Find CSS declarations that fail after `var()` substitution](https://recursiveai.org/onehtml/go/cookbook/find-invalid-css-computed-declarations/)
- [Resolve font-relative CSS lengths in Go](https://recursiveai.org/onehtml/go/cookbook/resolve-css-ch-ex-with-font-metrics/)
## The short answer
Call `doc.Style().Registrations()` to list valid `@property` rules. Each entry gives you the name, syntax, initial value, and inheritance flag. To see the value on one element, use `ComputedStyle(node).Get("--gap")` instead. A registration can say that the default is `4px` even while a particular element uses `12px`.
## What is `@property` in CSS?
[`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@property) registers a custom property. An ordinary `--gap` declaration supplies a value in a selector’s scope. Registration defines how that name works throughout the document: in this case `syntax: ""` expects a length, `inherits: false` disables default inheritance, and `initial-value: 4px` supplies a default. The `var(--gap)` reference in `margin-left` uses the custom property’s computed value for that element.
The [registration inspector](https://pkg.go.dev/recursiveai.org/go/onehtml@v1.1.1#Styles.Registrations) returns one entry per name, sorted by name. The last valid registration in stylesheet order wins. That makes the list useful for inventorying design tokens, but it doesn’t tell you which selector assigned a value to a given component. It isn’t a list of every `--name` declaration either: unregistered variables may be in use without appearing in the list.
## What does `inherits` control in a custom `@property` declaration?
A custom property declared without registration inherits by default. With a registration, the `inherits` descriptor lets you change that. In the example, the outer element explicitly sets `--gap` to `12px`. The inner element doesn’t set `--gap`, so with `inherits: false` it uses `4px`. If you switch to `inherits: true` as in the variation, the same inner element receives `12px`. An explicit valid assignment on the inner element can still set its own value.
For a component where callers are meant to set a spacing token on an ancestor, check the inheritance flag before looking for a selector bug. For a token that’s supposed to reset inside each component, check the opposite: compare a parent with an explicit value and a child without one. Reading only the registration won’t tell you whether the component’s own styles also assign the token.
## When does CSS use the `@property` initial value?
The [initial value](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@property/initial-value) is the registered default. A non-inheriting registration uses it when the element has no assignment. A value that doesn’t fit the registered syntax is treated as unset by onehtml-go, so whether inheritance applies still matters. This is distinct from the optional fallback in `var()`: if a custom property already resolves to its registered `4px`, the consumer has a value and needs no substitution fallback.
When reading the Go result, check `HasInitialValue` if the distinction between an omitted default and a supplied one matters. The universal syntax `"*"` is the case where the rule can omit it. For typed registrations, inspect the reported initial value and then compute the value of the element you actually care about.
# Check HTML for WCAG 2.2 AA and export SARIF in Go
**onehtml-go** is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onehtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-go) · [Docs](https://recursiveai.org/onehtml/go/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/go/cookbook/check-wcag-22-aa-and-export-sarif/check-wcag-22-aa-and-export-sarif.zip)
Use the WCAG 2.2 AA profile and `WriteSARIF` to report findings in CI. A scan can’t prove conformance. SARIF is a JSON format for analysis results that tools like [GitHub code scanning](https://docs.github.com/en/code-security/concepts/code-scanning/sarif-files) can display.
```shell
go get recursiveai.org/go/onehtml
```
Requires Go 1.24 or later.
```go
package main
import (
"fmt"
"os"
"recursiveai.org/go/onehtml"
v "recursiveai.org/go/onehtml/accessibility/validation"
)
func main() {
src, err := os.ReadFile("page.html")
if err != nil {
panic(err)
}
doc, err := onehtml.ParseBytes(src)
if err != nil {
panic(err)
}
profile := v.WithProfile(v.ProfileWCAG22AA)
report, err := v.Check(doc, profile)
if err != nil {
panic(err)
}
file, err := os.Create("accessibility.sarif")
if err != nil {
panic(err)
}
err = report.WriteSARIF(file,
v.WithExportURL("page.html"))
closeErr := file.Close()
if err != nil {
panic(err)
}
if closeErr != nil {
panic(closeErr)
}
for result := range report.WithOutcome(v.Failed) {
fmt.Println(result.RuleID)
}
fmt.Println("Wrote accessibility.sarif")
}
```
If `page.html` is missing, the file read fails before any SARIF is written. The program prints confirmed failures; open `accessibility.sarif` for locations and review items too.
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/check-wcag-22-aa-and-export-sarif/check-wcag-22-aa-and-export-sarif.zip) and `go run .`.
Save this input as `page.html` next to `main.go` if you’re pasting the code. It’s already in the zip.
```html
Shop
Shop
```
`go run .` prints:
```text
button-name
Wrote accessibility.sarif
```
## Variations
To fail CI on a confirmed accessibility issue, add this at the end of `main`, after the report is closed. The sample exits with status 1 after printing `button-name button`. `result.Target.Name()` gives the element name, `button`.
```go
for result := range report.WithOutcome(v.Failed) {
fmt.Println(result.RuleID, result.Target.Name())
os.Exit(1)
}
```
## Related recipes
- [Edit HTML attributes without reformatting in Go](https://recursiveai.org/onehtml/go/cookbook/edit-html-attributes-without-reformatting/)
- [Get computed CSS styles without a browser in Go](https://recursiveai.org/onehtml/go/cookbook/compute-css-style-without-browser/)
## The short answer
Parse the HTML, call `validation.Check` with `validation.WithProfile(validation.ProfileWCAG22AA)`, and pass a file to `report.WriteSARIF`. Upload that file to a SARIF-capable CI viewer or save it as a build artifact. Treat confirmed failures and items that need human review separately.
## How do I check a website for WCAG?
Run the checker on the HTML your build actually serves, not just the template that produces it. Template expansion may decide whether a button gets a name or whether a page gets a title. This example reads the generated input from disk, so it checks exactly the bytes in `page.html`. The [WCAG 2.2 standard](https://www.w3.org/TR/WCAG22/#cc2) defines Level AA in terms of all applicable Level A and AA criteria. The profile picks relevant library rules; it does not turn that rule set into exhaustive coverage of the standard.
For example, the checker can report that the sample’s button has no accessible name. It also marks whether the title is descriptive as a review item: seeing the word “Shop” in a title does not establish that it adequately describes the page. To cover the rest of the experience, use [W3C’s evaluation guidance](https://www.w3.org/WAI/test-evaluate/) and test the rendered page, including keyboard use and the states users encounter after interacting with it. onehtml-go does not run scripts or render the page.
## How do I report accessibility failures in CI with SARIF?
Use the checked file’s path as the artifact URI. `WithExportURL("page.html")` labels the result with that path; for a real build, use a path your viewer can resolve. This report marks `button-name` as `kind: fail` and points to `page.html`, line 6, column 3. It also contains `kind: review` items at `level: none`, so a panel that only shows errors can miss work you still need someone to review. Passed and inapplicable items are omitted by default.
Writing the file and enforcing your CI policy are separate steps. Write and close the file first, then use `report.WithOutcome(validation.Failed)` to decide the job’s exit status, as in the variation. Configure the artifact step to run even after a failed check, so the report is available when the build that produced it goes red. If you review ambiguous cases manually, do not silently treat the absence of `Failed` outcomes as a clean accessibility evaluation.
# Find CSS declarations invalid at computed-value time in Go
**onehtml-go** is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onehtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-go) · [Docs](https://recursiveai.org/onehtml/go/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/go/cookbook/find-invalid-css-computed-declarations/find-invalid-css-computed-declarations.zip)
A CSS declaration can win the cascade and still fail when `var()` is resolved. Find those failures with `Styles.InvalidDeclarations()`. Requires Go 1.24 or later.
```shell
go get recursiveai.org/go/onehtml
```
```go
package main
import (
"fmt"
"log"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
const html = `
Card
`
doc, err := onehtml.Parse(strings.NewReader(html))
if err != nil {
log.Fatal(err)
}
for node, decl := range doc.Style().InvalidDeclarations() {
id, _ := node.Get("id") // Optional label.
fmt.Printf("%s %s: %s (%s)\n",
id, decl.Property, decl.Value,
decl.Source.Selector)
}
}
```
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/find-invalid-css-computed-declarations/find-invalid-css-computed-declarations.zip) and `go run .`.
```text
card padding: var(--pad) var(--missing) (p)
card width: var(--pad) var(--pad) (p)
```
The report includes the element ID, property, original value, and selector. An empty report does not mean the source has no CSS errors: declarations rejected during parsing are not listed.
## Variations
To check only the card, replace the document-wide loop with this loop. `doc` is the document from the example.
```go
node := doc.ElementByID("card")
style := doc.Style().ComputedStyle(node)
for _, decl := range style.InvalidDeclarations() {
fmt.Println(decl.Property)
}
```
This prints `padding` and `width`, one per line. If no element has the requested ID, `ElementByID` returns the zero `onehtml.Node`, whose `Valid()` method returns `false`.
## Related recipes
- [Read CSS custom property registrations](https://recursiveai.org/onehtml/go/cookbook/register-css-custom-properties/)
- [Find elements with CSS selectors in Go](https://recursiveai.org/onehtml/go/cookbook/parse-html-and-query-css-selectors/)
## The short answer
Range over `doc.Style().InvalidDeclarations()` to get the affected node and the failed declaration. Read `Property`, `Value`, and `Source.Selector` to find the rule to fix. This is a computed-style diagnostic, not a CSS syntax checker: it tells you what failed after the cascade picked a winner for an element.
## What does “invalid at computed-value time” mean in CSS?
A declaration using `var()` can look valid until the engine substitutes the variable. In the example, `padding` fails because `--missing` has no value or fallback. `width` fails for a different reason: both variables resolve, leaving `4px 4px`, which is not a valid single width. A variable can be valid in its own right and still make the property that consumes it invalid.
The [CSS Custom Properties specification](https://www.w3.org/TR/css-variables-1/#invalid-variables) explains how these failures differ from parse-time ones. A declaration discarded while parsing never has a chance to win. A declaration that fails at computed-value time has already won; CSS doesn’t go back and try a lower-priority declaration for that property. It behaves as if `unset`: an inherited property takes its inherited value, and a non-inherited one takes its initial value.
For a shorthand such as `padding`, one failing substitution can invalidate the whole shorthand. The Go report uses the shorthand’s own name rather than repeating it for each side of the box.
## How do you fix a CSS variable error with a fallback?
First distinguish a missing variable from a value of the wrong type or shape. A [fallback inside `var()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/var) can fix a missing variable: replacing `var(--missing)` with `var(--missing, 8px)` lets this `padding` declaration resolve to `4px 8px`. The fallback must be valid where it lands. It would not fix `width`: two valid lengths are still invalid there, so that declaration needs just one `var(--pad)`.
```css
padding: var(--pad) var(--missing, 8px);
width: var(--pad);
```
With both changes, the example’s loop prints no rows. A fallback supplied as a separate, earlier `width` declaration is not the same fix. By the time the later `var()` declaration fails, the cascade has already selected it.
## Why does a CSS variable work on one element but not another?
The same rule can see different custom property values on different elements. A selector tells you where the rule came from; the node tells you which instance actually failed. Keep both in reports for repeated components. For a page-wide check, consume the whole [`Styles.InvalidDeclarations()` iterator](https://pkg.go.dev/recursiveai.org/go/onehtml@v1.1.1#Styles.InvalidDeclarations). It computes styles as it walks the document. If you stop after the first failure, later elements are not checked by that walk. For an inspector where you’ve already selected an element, use the single-style method shown in the variation.
# Resolve CSS ch and ex units in Go
**onehtml-go** is a free, open-source HTML parser for Go from Recursive AI, with CSS selectors, computed styles, lossless editing and accessibility checks. MIT or Apache-2.0, no dependencies.
[pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onehtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-go) · [Docs](https://recursiveai.org/onehtml/go/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/go/cookbook/resolve-css-ch-ex-with-font-metrics/resolve-css-ch-ex-with-font-metrics.zip)
`ch` uses the advance of `0`, and `ex` uses the height of `x`. Use `WithFontMetrics` to supply each measurement as a fraction of the font size, such as `XHeight: 0.55` for an x-height that’s 55% of the font size. Requires Go 1.24 or later.
```shell
go get recursiveai.org/go/onehtml
```
```go
package main
import (
"fmt"
"log"
"strings"
"recursiveai.org/go/onehtml"
)
func main() {
const html = `
Sample text
`
doc, err := onehtml.Parse(strings.NewReader(html))
if err != nil {
log.Fatal(err)
}
metrics := onehtml.WithFontMetrics(
func(q onehtml.FontQuery) onehtml.FontMetrics {
if len(q.Families) > 0 && q.Families[0] == "Demo" {
return onehtml.FontMetrics{
XHeight: 0.55, ZeroAdvance: 0.62,
}
}
return onehtml.FontMetrics{}
},
)
node, err := doc.SelectFirst("p")
if err != nil {
log.Fatal(err)
}
style := doc.Style(metrics).ComputedStyle(node)
fmt.Println(style.Get("margin-left"))
fmt.Println(style.Get("padding-left"))
}
```
Paste the code above into main.go, run `go mod init example` and `go get recursiveai.org/go/onehtml`, then `go run .`; or unzip [the example](https://recursiveai.org/onehtml/go/cookbook/resolve-css-ch-ex-with-font-metrics/resolve-css-ch-ex-with-font-metrics.zip) and `go run .`.
```text
22px
37.2px
```
The callback supplies example ratios for a font named `Demo`; no font file is needed. If a requested metric is zero, onehtml-go uses an estimate for that metric.
## Variations
To compare with the estimates, add this to the end of `main`. `doc` and `node` are from the example.
```go
estimated := doc.Style().ComputedStyle(node)
fmt.Println(estimated.Get("margin-left"))
fmt.Println(estimated.Get("padding-left"))
```
The two additional lines are `20px` and `30px`.
## Related recipes
- [Read typed CSS custom properties](https://recursiveai.org/onehtml/go/cookbook/register-css-custom-properties/)
- [Report invalid computed CSS declarations](https://recursiveai.org/onehtml/go/cookbook/find-invalid-css-computed-declarations/)
## The short answer
Pass a callback to `onehtml.WithFontMetrics` and pass the option to `doc.Style()`. Return `XHeight` for `ex` and `ZeroAdvance` for `ch`, both as fractions of the font size, not pixel values. In the sample, `2ex` is `2 × 0.55 × 20px = 22px`, and `3ch` is `3 × 0.62 × 20px = 37.2px`.
## What are `ch` and `ex` in CSS?
They are [font-relative CSS lengths](https://www.w3.org/TR/css-values-4/#font-relative-lengths). `ch` is based on the advance of the digit zero: the space the glyph takes along the line, not the width of its painted outline. `ex` is based on x-height, the height of the lowercase “x.” A length such as `30ch` does not promise that 30 arbitrary characters will fit. In a proportional font, “W” and “i” can advance by different amounts even though a `ch` length is computed from just one glyph.
Unlike `em`, which uses the relevant font size, `ch` and `ex` depend on the font’s shapes and spacing as well as its size. Changing font family at the same `font-size` can change padding, margins, and other lengths expressed in those units. Also distinguish `rch` and `rex`: they are relative to the root element’s font rather than the local font. The [Go metrics hook](https://pkg.go.dev/recursiveai.org/go/onehtml@v1.1.1#WithFontMetrics) can supply metrics for both forms.
## How do you convert `ch` and `ex` to pixels when the font is unknown?
There is no fixed conversion for an arbitrary font. onehtml-go does not load fonts; without a supplied measurement it estimates both units at half an em. For a `20px` font, that gives `10px` per unit, as shown in the variation. The estimate applies per field: if you know the zero advance but not the x-height, set `ZeroAdvance` and leave `XHeight` zero. Treat the estimated lengths as estimates, not measurements of an installed font.
If you do know the font, normalize its metrics to its font size before returning them. For example, an x-height of `11px` measured at `20px` corresponds to `XHeight: 0.55`, not `XHeight: 11`. The style engine applies the font size. A wrong unit in the callback will scale every CSS length that uses the returned metric.
## Which font does CSS use for a `ch` or `ex` measurement?
Use the primary face your application would draw with. [`FontQuery`](https://pkg.go.dev/recursiveai.org/go/onehtml@v1.1.1#FontQuery) gives you the computed list of families in order, plus weight, style, and stretch. The example recognizes only the single family in its input. With a list, use the first family you can supply a face for and choose metrics for the matching face, not one shared set of numbers for every weight or style.
The callback may be called from any goroutine computing styles, and the library keeps its answer per distinct query. Use a concurrency-safe lookup. These values describe the computed CSS lengths; the library does not lay out the page or measure the rendered text.