csscolorparser
csscolorparser is a single-file CommonJS parser for older CSS color syntax. Call parseCSSColor with a string and it returns [red, green, blue, alpha], using integer RGB channels from 0 to 255 and alpha from 0 to 1, or null when the outer syntax is not recognized. It understands named CSS colors, transparent, three- and six-digit hex, comma-based rgb()/rgba(), and comma-based hsl()/hsla(). The code intentionally accepts some nonstandard input, clamps out-of-range channels, and predates most modern CSS Color syntax.
csscolorparser is acceptable as frozen compatibility code for an old, narrow color grammar. Do not install it as a general CSS validator or modern color parser; its missing syntax and NaN-producing edge cases make maintained alternatives safer.
Use it if
- You maintain a dependency that already expects this exact four-element RGBA array contract
- Your accepted input is deliberately limited to CSS Color 3-era names, hex, comma RGB, and comma HSL forms
- You need a dependency-free CommonJS parser small enough to inspect and vendor locally
- You want permissive clamping of numeric channels rather than strict CSS validation
- You accept current CSS: version 1.0.3 has no four- or eight-digit hex, space-separated rgb()/hsl(), slash alpha, lab(), lch(), oklab(), oklch(), color(), color-mix(), or currentColor support
- You need validation rather than best-effort conversion: malformed functional channels can produce arrays containing NaN, and parseInt allows some partially valid numeric text instead of consistently returning null
- You want active maintenance: the npm release and last default-branch commit are from August 2016, while the repository's later push came from an unmerged documentation pull request
- You need TypeScript or ESM packaging: the package has no declarations, export map, ESM build, browser field, or documented bundler entry beyond its CommonJS main file
- You need standards-accurate whitespace and HSL rules: the source removes ordinary spaces only and explicitly permits non-percentage saturation and lightness even though its comment says that is not spec compliant
Setup reality
npm install csscolorparser gives you one dependency-free CommonJS file. Import the named export with const { parseCSSColor } = require('csscolorparser'); the package does not export the function directly, does not provide TypeScript types, and does not publish an ESM entry. There are no peers, native builds, credentials, config files, or initialization steps. The real setup task is deciding and enforcing the input contract around it. A successful-looking four-item array is not proof of a valid CSS color: component parsing uses parseInt and parseFloat, so text such as rgb(nope, 0, 0) can return [NaN, 0, 0, 1], and partially parsed values may be accepted. Check result !== null and Number.isFinite on every component when input is not fully trusted. Values outside the nominal range are clamped, percentages are rounded to byte channels, hue wraps around 360 degrees, and HSL saturation/lightness decimals are accepted even though CSS requires percentages for this old syntax. The parser lowercases input and removes literal space characters everywhere, but tabs and newlines are not normalized. It supports commas only, so browser-valid modern strings such as rgb(1 2 3 / 50%) fail. Named-color arrays are copied before return, which means callers can mutate their result without changing the internal table. If current browser parity matters, the surrounding validation and missing syntax quickly cost more than installing a maintained parser.
Patterns
Parse a supported CSS colorparse-color
const { parseCSSColor } = require('csscolorparser');
const rgba = parseCSSColor('rgba(255, 128, 12, 0.5)');
// [255, 128, 12, 0.5]The package exports an object containing parseCSSColor, not the parser function as module.exports itself.
Resolve a named CSS colorparse-named-color
const purple = parseCSSColor('rebeccapurple');
// [102, 51, 153, 1]
const clear = parseCSSColor('transparent');
// [0, 0, 0, 0]Input is lowercased, so names are case-insensitive. Only the hard-coded table from this package is available.
Parse three- or six-digit hexparse-hex-color
parseCSSColor('#0af'); // [0, 170, 255, 1]
parseCSSColor('#00aaff'); // [0, 170, 255, 1]Four- and eight-digit hex forms such as #0af8 and #00aaff88 are unsupported and return null.
Parse percentage RGB channelsparse-rgb-percentages
parseCSSColor('rgb(100%, 50%, 0%)');
// [255, 128, 0, 1]Percentage channels are multiplied by 255 and rounded, matching the source's stated Chrome-inspired behavior.
Convert comma-based HSL to RGBAparse-hsl-color
parseCSSColor('hsl(210, 100%, 50%)');
// [0, 128, 255, 1]
parseCSSColor('hsla(210, 100%, 50%, 25%)');
// [0, 128, 255, 0.25]Only the comma syntax is recognized. Modern hsl(210 100% 50% / 25%) returns null.
Reject null and non-finite channelsvalidate-parse-result
function parseSafeColor(input) {
const rgba = parseCSSColor(input);
if (!rgba || !rgba.every(Number.isFinite)) {
throw new TypeError(`Invalid supported color: ${input}`);
}
return rgba;
}Checking only for null is insufficient because malformed numeric components can produce an array containing NaN.
Turn the result back into rgba() textformat-rgba-output
function toRgbaString(input) {
const [r, g, b, a] = parseSafeColor(input);
return `rgba(${r}, ${g}, ${b}, ${a})`;
}
toRgbaString('slateblue');
// rgba(106, 90, 205, 1)The library only parses; it has no serializer, hex formatter, precision option, or color object API.
Use a fallback for unsupported syntaxhandle-invalid-color
const parsed = parseCSSColor(userColor);
const rgba = parsed && parsed.every(Number.isFinite)
? parsed
: [0, 0, 0, 1];Unsupported modern CSS and malformed outer syntax return null, while some malformed components yield NaN, so guard both cases.
Account for automatic channel clampingobserve-channel-clamping
parseCSSColor('rgba(300, -20, 12.6, 2)');
// [255, 0, 13, 1]Out-of-range RGB and alpha values are accepted and clamped rather than rejected. Do not use this behavior for strict syntax validation.
Use wrapped hue valuesnormalize-hue
parseCSSColor('hsl(420, 100%, 50%)');
parseCSSColor('hsl(60, 100%, 50%)');
// both produce [255, 255, 0, 1]Hue is normalized modulo 360, including negative values. Saturation and lightness are clamped into the 0 to 1 range.
Compute luminance from parsed channelscompute-relative-luminance
function luminance(input) {
const [r, g, b] = parseSafeColor(input).map((v, i) => i < 3 ? v / 255 : v);
const linear = [r, g, b].map((c) =>
c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
);
return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}Alpha is ignored here. Composite translucent colors over their actual background before using luminance for a contrast decision.
Mutate a parsed result without changing the color tableavoid-result-aliasing
const first = parseCSSColor('red');
first[0] = 0;
const second = parseCSSColor('red');
// second is still [255, 0, 0, 1]Named-color entries are returned with slice(), so each call gets a fresh array. Other parsed forms also allocate new arrays.
Alternatives
| Package | Registry | Pick it when |
|---|---|---|
| color-string | npm | You want a focused maintained parser and serializer with broader CSS color syntax |
| colord | npm | You want a small TypeScript-friendly color toolkit with parsing, conversion, and optional plugins |
| color | npm | You need a chainable object API for conversions, mixing, contrast, and output formatting |
| tinycolor2 | npm | You support an established browser codebase that already uses TinyColor's permissive API |