Define what “nearest name” means
CSS Color Module Level 4 defines a table of named colors whose keywords resolve to specific sRGB values. A nearest-name tool can treat those entries as candidate points, but the specification does not say that every other color owns one of those names. The tool therefore answers a narrow question: which candidate has the smallest numerical distance under this implementation? It does not determine a cultural name, a paint standard, a brand token, or what every observer will call the sample.
- State that the candidate set is the CSS named-color table, not an unlimited color dictionary.
- Present the keyword and its exact reference value together so the result is independently checkable.
- Label the result “nearest” or “approximate” and avoid claiming that the input is literally that named color.
Build a canonical candidate table
Load each keyword and exact sRGB triplet from one versioned source rather than copying values through several generators. Normalize keyword casing for lookup while preserving the canonical spelling used in output. Several CSS keywords are aliases with identical coordinates: aqua and cyan, fuchsia and magenta, plus gray and grey variants such as darkgray and darkgrey. A distance calculation cannot distinguish aliases because their coordinates are equal. Group aliases or choose one representative by an explicit stable rule instead of relying on database row order.
- Store integer red, green, and blue channels from 0 through 255 and derive other spaces from those source values.
- Keep aliases attached to the same coordinate so an exact match can disclose every equivalent CSS keyword.
- Exclude the special transparent keyword from an opaque nearest-color search, or handle alpha in a separate documented mode.
Normalize the input before comparison
Parse the input as a color, validate its range, and convert it to the same representation used for every candidate. Six-digit HEX maps directly to encoded sRGB bytes, but CSS can express colors in many syntaxes and spaces. Converting Display P3 or Lab to sRGB may place a color outside the sRGB gamut, so a tool must state whether it clips, maps, or rejects that value. Alpha adds another dependency: a translucent color has no single visible result until it is composited over a known background.
- Reject malformed input instead of silently repairing ambiguous digits, missing channels, or unsupported syntax.
- For an opaque sRGB catalog, document the gamut policy and show the normalized sRGB value actually compared.
- For alpha below one, require a background and a defined compositing method, or report that nearest-name comparison is unavailable.
Choose a distance metric deliberately
Straight-line distance between encoded red, green, and blue numbers is easy and deterministic, but encoded sRGB channels are nonlinear and equal numeric steps are not intended to be equal perceptual steps. Converting both colors to CIE Lab permits Delta E 76, the Euclidean distance in Lab. Delta E 2000 adds corrections for known nonuniformities in lightness, chroma, and hue. OKLab offers another perceptual coordinate system, and CSS Color 4 documents a simple Euclidean Delta E OK measure. These formulas can rank the same candidates differently.
- Use encoded-sRGB distance only when simplicity and compatibility are the declared goals, not as a perceptual claim.
- Use one precise conversion pipeline and metric version for every candidate; never mix Lab, OKLab, and byte channels.
- Publish the metric name with the result because a bare distance number has no meaning without its formula and scale.
Calculate and break ties reproducibly
After conversion, calculate the selected distance from the input to every canonical candidate, retain the minimum, and apply a documented tie policy. Floating-point comparisons need care: exact aliases should be recognized from their shared source coordinate, while nearly equal distances should not be declared tied by an arbitrary large tolerance. Keep enough precision during conversion and round only for display. A stable secondary ordering, such as canonical keyword order, makes repeated runs and different database query plans return the same representative.
- Return distance zero for an exact source-coordinate match and include its alias group when applicable.
- Compare full-precision computed distances, using only a narrowly specified tolerance justified by the numeric implementation.
- Sort equal results by a fixed canonical key and test that insertion order, locale, and database collation cannot alter the winner.
Explain the result without overstating it
A useful response includes the input after normalization, the winning CSS keyword, that keyword’s exact sRGB or HEX value, the metric, and the measured distance. It may also show several nearest candidates, because a single winner can conceal a close ranking. Do not convert distance into an unsupported percentage of similarity. Thresholds such as “indistinguishable” depend on the metric, viewing conditions, display, surrounding colors, observer, and task; a catalog lookup has not measured all of those conditions.
- Show enough numeric detail to reproduce the comparison while rounding presentation values consistently.
- Offer the top few candidates when distances are close, but preserve one deterministic result for URLs and APIs.
- Separate “nearest CSS keyword” from editorial names, localized names, accessibility judgments, or palette recommendations.
Verify the implementation with fixed tests
Tests should protect the candidate data, conversion pipeline, metric, and tie behavior separately. Every named color must match itself at distance zero. Alias pairs must produce the same coordinates. Reference conversion examples should be checked within a stated numeric tolerance, and boundary inputs such as black, white, channel limits, mixed case HEX, and out-of-gamut colors should follow the documented policy. Finally, snapshot a small set of nearest rankings so a dependency or formula change cannot silently rewrite indexed pages.
- Validate table completeness and uniqueness by canonical keyword while allowing explicitly recorded coordinate aliases.
- Test malformed syntax, alpha handling, gamut handling, exact matches, close rankings, and deterministic tie resolution.
- Version the algorithm and recompute results intentionally when the candidate set, conversion code, or distance metric changes.
Primary sources
The factual claims in this article are checked against these published specifications.