@pbroom/color-kitConversion

toCss

Serialize a Color as a CSS color string in the given format.

functionimport { toCss } from '@pbroom/color-kit';index.ts:467
function toCss(  color: Color, ,  format?: CssColorFormat,): string;

'hex' and 'rgb' clip to sRGB and round to 8-bit like toRgb; 'hsl' clips to sRGB (1 decimal); 'display-p3' clips to P3 (4 decimals); 'oklch' and 'oklab' are exact (4 decimals, hue 2). An alpha below 1 is appended as / alpha (3 decimals), or as the aa byte for hex.

Parameters

colorColor
Color to serialize
format?CssColorFormatdefault 'hex'
Output format

Returns

stringCSS color string

Throws

  • When format is not a CssColorFormat (the message points 'p3' at 'display-p3')
  • When any channel of color is not finite

Example

TypeScript
import { parse, toCss } from '@pbroom/color-kit';

const blue = parse('#3b82f6');
toCss(blue); // → '#3b82f6'
toCss(blue, 'oklch'); // → 'oklch(0.6231 0.188 259.81)'
toCss(blue, 'display-p3'); // → 'color(display-p3 0.3047 0.5035 0.9338)'

See also