parse
Parse a CSS color string into a Color.
import { parse } from '@pbroom/color-kit';parse.ts:96function parse(input: string): Color;Supports CSS Color 4: hex (#rgb, #rgba, #rrggbb, #rrggbbaa), the 148 named colors and transparent, rgb() / rgba() and hsl() / hsla() (modern space syntax and legacy comma syntax), hwb(), lab(), lch(), oklab(), oklch(), and color() with srgb, srgb-linear, display-p3, rec2020, a98-rgb, prophoto-rgb, xyz, xyz-d65 and xyz-d50. Components accept numbers, percentages, and none (a missing component, which CSS treats as 0; not allowed in legacy comma syntax). Hues accept deg, grad, rad and turn, and the result's hue is normalized to [0, 360). Input is trimmed and case-insensitive. Colors outside sRGB (wide-gamut color(), oklch(), lab(), ...) keep their full chroma; nothing is gamut mapped.
Use tryParse to get null instead of an exception.
Parameters
- input
string - CSS color string
Returns
Throws
- When
inputis not a supported, well-formed CSS color: unknown names or functions, invalid hex digits or lengths, the wrong number of components, malformed numbers (1.2.3), units a component does not accept, and values that overflow toInfinityas written or after conversion - When
inputis not a string
Example
import { parse, toCss, toHex } from '@pbroom/color-kit';
parse('oklch(0.7 0.15 30)'); // → { l: 0.7, c: 0.15, h: 30, alpha: 1 }
toCss(parse('rebeccapurple'), 'oklch'); // → 'oklch(0.4403 0.1603 303.37)'
parse('rgb(59 130 246 / 50%)').alpha; // → 0.5
toHex(parse('color(display-p3 1 0 0)')); // → '#ff0000' (clipped by toHex)
parse('not-a-color'); // throws Error: Unable to parse color: "not-a-color"