CSS Color Parser

Try it out

rgb(88, 186, 0) color(display-p3 0.41387 0.73323 0) oklch(0.7 0.268 134.568)

One more specialized parser

Plenty of plugins in postcss-preset-env interact with CSS color values. We provide fallbacks for modern notations like rgb(255 0 255 / 50%) and new color functions like color(display-p3 0.5 0 0.5 / 0.5).

In the past, each package had its own implementation of the needed conversion logic. This was fine for a while, but as the number of plugins grew, so did the amount of duplicate code. This was harder to maintain and plugins were larger than they needed to be.

We had initially hoped to use an existing package (e.g. color.js or culori), but no package was designed specifically to parse and convert CSS colors exactly as a browser would. We hope that our modular approach allows others to reuse bits even if their use case is different.

css-color-5 introduced recursive color functions which required a different class of tools.
Simple parsing algorithms or regular expressions were no longer sufficient.

A recursive example :

.example {
	color: color-mix(
		in lch,
		#d20 50%,
			in srgb,
			rgb(230 10 15) 10%

We started from our existing tokenizer and parsing algorithms and added @csstools/css-calc on on top of that.

We also created and published the @csstools/color-helpers npm package with the color logic based on the sample code maintained by the CSS Working Group. We are not the creators of most of the algorithms in this package but our users require something distributed through npm.

@csstools/color-helpers contains all the parts needed to convert between color spaces and color notations, but it doesn't have any knowledge of CSS and isn't able to parse or serialize CSS color values.

We brought all these building blocks together in a new package @csstools/css-color-parser.

This package is able to parse CSS color values like a browser would and convert them to fallback notations.

Currently supported in the parser :

Only two serialization formats are currently supported :

If you require other formats, please open an issue

rgba(255, 99, 0, 0.339833) color(display-p3 0.9361 0.42808 0.14191 / 0.339833)

oklch(0.69433 0.21132 43.7908 / 0.34)