Color

Format colors as CSS, ANSI, numbers, hex strings, and more

Bun.color(input, outputFormat?) uses Bun's CSS parser to parse, normalize, and convert colors from user input to any of these output formats:

FormatExample
"css""red"
"ansi""\x1b[38;2;255;0;0m"
"ansi-16""\x1b[91m"
"ansi-256""\x1b[38;5;196m"
"ansi-16m""\x1b[38;2;255;0;0m"
"number"0x1a2b3c
"rgb""rgb(255, 99, 71)"
"rgba""rgba(255, 99, 71, 0.5)"
"hsl""hsl(120, 50%, 50%)"
"hex""#1a2b3c"
"HEX""#1A2B3C"
"{rgb}"{ r: 255, g: 99, b: 71 }
"{rgba}"{ r: 255, g: 99, b: 71, a: 1 }
"[rgb]"[ 255, 99, 71 ]
"[rgba]"[ 255, 99, 71, 255]

Use it to:

  • Validate and normalize colors to persist in a database (number is the most database-friendly)
  • Convert colors to different formats
  • Color terminal output beyond the basic 16 colors (use ansi to auto-detect terminal color support, or ansi-16, ansi-256, or ansi-16m to target a specific color depth)
  • Format colors for use in CSS injected into HTML
  • Get the r, g, b, and a color components as JavaScript objects or numbers from a CSS color string

It's a built-in alternative to the npm packages color and tinycolor2, with full support for parsing CSS color strings and zero dependencies.

Flexible input#

Bun.color accepts any of the following:

  • Standard CSS color names like "red"
  • Numbers like 0xff0000
  • Hex strings like "#f00"
  • RGB strings like "rgb(255, 0, 0)"
  • RGBA strings like "rgba(255, 0, 0, 1)"
  • HSL strings like "hsl(0, 100%, 50%)"
  • HSLA strings like "hsla(0, 100%, 50%, 1)"
  • RGB objects like { r: 255, g: 0, b: 0 }
  • RGBA objects like { r: 255, g: 0, b: 0, a: 1 }
  • RGB arrays like [255, 0, 0]
  • RGBA arrays like [255, 0, 0, 255]
  • LAB strings like "lab(50% 50 50)"
  • ... anything else that CSS can parse as a single color value

Format colors as CSS#

The "css" format outputs valid CSS for use in stylesheets, inline styles, CSS variables, or CSS-in-JS. It returns the most compact string representation of the color.

Bun.color("red", "css"); // "red"
Bun.color(0xff0000, "css"); // "red"
Bun.color("#f00", "css"); // "red"
Bun.color("#ff0000", "css"); // "red"
Bun.color