mrkeyoor.com_
Sat 08 Aug 22:48 UTC
npmWeb Frontendupdated 08 Aug 2026

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.

Verdict

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.

API stability4/5The package exposes one named function and has kept the same [r, g, b, a] return shape since its early releases. Its source is short, has no dependencies, and copies named-color arrays before returning them, so there are few moving pieces. That frozen behavior is useful for compatibility. It loses a point because permissive parseInt and parseFloat behavior, NaN components, clamping, and nonstandard HSL decimals are effectively accidental API commitments that a proper standards update could not preserve cleanly.
Docs2/5The README is essentially a console transcript. It shows named colors, three- and six-digit hex, RGBA, HSL, invalid input returning null, hue wrapping, and the intentionally noncompliant HSL decimal case. It does not explain the CommonJS export shape, channel ranges, clamping, NaN results, whitespace rules, unsupported modern syntax, or browser integration. There is no separate documentation site or test suite, so accurate edge-case work requires reading the single source file.
Maintenance1/5Version 1.0.3 and the latest commit on the default branch date to August 2016. GitHub is not marked archived, but the only later repository push is tied to an unmerged 2021 documentation pull request. Another open pull request adding four- and eight-digit hex has waited since 2017. With CSS Color evolving substantially since the release, the absence of published standards updates, tests, issue response, and package changes is a material maintenance risk.
Ecosystem2/5The npm package recorded 3,405,917 downloads for the measured week, which indicates substantial transitive use in established tooling. Direct community signals are much smaller: the repository has 37 stars, 27 forks, two open pull requests, no declared TypeScript support, and no extensions or companion packages documented. Its zero-dependency shape makes it easy for other packages to retain, but new color-processing libraries rarely build an ecosystem around this parser.

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
Skip it if

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

PackageRegistryPick it when
color-stringnpmYou want a focused maintained parser and serializer with broader CSS color syntax
colordnpmYou want a small TypeScript-friendly color toolkit with parsing, conversion, and optional plugins
colornpmYou need a chainable object API for conversions, mixing, contrast, and output formatting
tinycolor2npmYou support an established browser codebase that already uses TinyColor's permissive API