color2k

Fully dynamic colors in 2.5 kB

color2k is a small JavaScript color library. Hand it a color while your app runs and it gives back the hover state and the text color that reads on top. It covers every 8-bit sRGB color, written as hex, rgb(a), hsl(a) or a CSS name. No dependencies.

npm i color2k
Quickstart

This page is built from one color. Turn the wheel, or tap any wedge.

Menu

Why color2k#

You have a brand color. You need its hover state, a faded version for the focus ring, and to know whether the text on top should be black or white. That is most of what an app does with color, and color2k does it in 2.5 kB.

  • It's small. All 25 exports come to 2.5 kB. Import only darken and you ship 1.6 kB.
  • It's just functions. Pass a CSS color string and get one back. There is nothing to set up or chain.
  • It covers the daily work. Parse and convert colors, lighten or darken them, mix them, build scales and check WCAG contrast.
  • It's boring to depend on. No dependencies, a test file for every function, TypeScript types and npm provenance. The build still runs on Node 6.

Functions

Six groups. In each one, every function runs on your color.

Start

Quickstart Install color2k and make your first calls

Install it, import a function and pass it a color.

npm i color2k
import { darken, mix, readableColor, toHex } from 'color2k';

darken('rebeccapurple', 0.1); // 'hsla(270, 50%, 30%, 1)'
mix('gold', 'tomato', 0.5); // 'rgba(255, 157, 36, 1)'
readableColor('gold'); // '#000'
toHex('rgb(102, 51, 153)'); // '#663399'

Colors go in as CSS strings. Amounts are decimals from 0 to 1.

color2k ships ES modules, CommonJS and a UMD build, so it works without a bundler too.

In Node.js with require:

const { darken } = require('color2k');

darken('white', 0.1); // 'hsla(0, 0%, 90%, 1)'

In the browser as a module:

<script type="module">
  import { darken } from 'https://esm.sh/color2k';
</script>

Or as a global named color2k:

<script src="https://unpkg.com/color2k"></script>

Browser and Node support#

The CommonJS build runs on Node 6, and CI runs it there on every change. The ES module and UMD builds are written in ES2015 syntax, so they load in any browser that understands ES2015 without a compile step. TypeScript types ship in the package.

This section as MarkdownBack to the top

Functions

Parse Parse CSS colors to RGBA and HSLA numbers

Two functions that read a color string into numbers. Everything else in color2k starts here.

parseToRgba(color)

Parses a color into red, green, blue, and alpha channel values.

Red74

Green53

Blue232

Alpha1

Try another spelling
parseToRgba('#4a35e8')
function parseToRgba(color: string): [number, number, number, number]

Reads hex (#rgb, #rgba, #rrggbb, #rrggbbaa), comma-separated rgb(), rgba(), hsl() and hsla(), CSS named colors, and transparent.

This is a lenient parser, not a validator. Most strings in none of these forms throw a ColorError, but not all: color names are matched by hash, so about 3% of made-up, letters-only names are read as some color instead. The numbers in rgb() and the alpha value are returned as written, without clamping: rgb(999, 0, 0) gives [999, 0, 0, 1].

parseToRgba('rgba(255, 0, 0, 0.5)'); // [255, 0, 0, 0.5]

Parameters

color string
The input color.

Returns

[number, number, number, number] A tuple in the order [red, green, blue, alpha].

1.46 kB imported alone Source

parseToHsla(color)

Parses a color into hue, saturation, lightness, and alpha channel values.

Saturation80%

Lightness56%

Alpha1

parseToHsla('#4a35e8')
function parseToHsla(color: string): [number, number, number, number]

Hue is a number between 0 and 360. Saturation, lightness, and alpha are decimal percentages between 0 and 1.

parseToHsla('red'); // [0, 1, 0.5, 1]

Parameters

color string
The input color.

Returns

[number, number, number, number] A tuple in the order [hue, saturation, lightness, alpha].

1.58 kB imported alone Source

This section as MarkdownBack to the top

Functions

Convert Convert hex to RGB and HSL in JavaScript

Write a color in another format, or build one from numbers.

toHex(color)

Converts a color to a hex color string.

toHex('#4a35e8')
function toHex(color: string): string

Includes an alpha channel when the input color is not fully opaque.

toHex('palevioletred'); // '#db7093'

Parameters

color string
The input color.

Returns

string A hex color string.

1.54 kB imported alone Source

toRgba(color)

Converts a color to an rgba color string.

toRgba('#4a35e8')
function toRgba(color: string): string
toRgba('midnightblue'); // 'rgba(25, 25, 112, 1)'

Parameters

color string
The input color.

Returns

string An rgba color string.

1.52 kB imported alone Source

toHsla(color)

Converts a color to an hsla color string.

toHsla('#4a35e8')
function toHsla(color: string): string
toHsla('peachpuff'); // 'hsla(28, 100%, 86%, 1)'

Parameters

color string
The input color.

Returns

string An hsla color string.

1.66 kB imported alone Source

rgba(red, green, blue, alpha)

Builds an rgba color string from red, green, blue, and alpha channel values.

rgba(74, 53, 232, 1)
function rgba(red: number, green: number, blue: number, alpha: number): string
rgba(255, 0, 0, 1); // 'rgba(255, 0, 0, 1)'

Parameters

red number
The red channel value from 0 to 255.
green number
The green channel value from 0 to 255.
blue number
The blue channel value from 0 to 255.
alpha number
The opacity as a decimal between 0 and 1.

Returns

string An rgba color string.

283 B imported alone Source

hsla(hue, saturation, lightness, alpha)

Builds an hsla color string from hue, saturation, lightness, and alpha channel values.

hsla(247, 0.8, 0.56, 1)
function hsla(hue: number, saturation: number, lightness: number, alpha: number): string
hsla(0, 1, 0.5, 1); // 'hsla(0, 100%, 50%, 1)'

Parameters

hue number
The color wheel angle in degrees. Any value wraps into 0 to 360.
saturation number
The saturation as a decimal between 0 and 1.
lightness number
The lightness as a decimal between 0 and 1.
alpha number
The opacity as a decimal between 0 and 1.

Returns

string An hsla color string.

312 B imported alone Source

This section as MarkdownBack to the top

Functions

Adjust Lighten and darken colors in JavaScript

Each of these changes your color one way and hands back the new one.

darken(color, amount)

Darkens a color by subtracting from the lightness channel in HSL space.

darken('#4a35e8', 0.15)
function darken(color: string, amount: number): string
darken('white', 0.1); // 'hsla(0, 0%, 90%, 1)'

Parameters

color string
The input color.
amount number
The amount to darken, given as a decimal between 0 and 1.

Returns

string The darkened color as an hsla string.

1.67 kB imported alone Source

lighten(color, amount)

Lightens a color by adding to the lightness channel in HSL space.

lighten('#4a35e8', 0.15)
function lighten(color: string, amount: number): string

This is equivalent to darken(color, -amount).

lighten('black', 0.1); // 'hsla(0, 0%, 10%, 1)'

Parameters

color string
The input color.
amount number
The amount to lighten, given as a decimal between 0 and 1.

Returns

string The lightened color as an hsla string.

1.68 kB imported alone Source

saturate(color, amount)

Saturates a color by adding to the saturation channel in HSL space.

saturate('#4a35e8', 0.2)
function saturate(color: string, amount: number): string

This is equivalent to desaturate(color, -amount).

saturate('hsl(0, 50%, 50%)', 0.1); // 'hsla(0, 60%, 50%, 1)'

Parameters

color string
The input color.
amount number
The amount to saturate, given as a decimal between 0 and 1.

Returns

string The saturated color as an hsla string.

1.68 kB imported alone Source

desaturate(color, amount)

Desaturates a color by subtracting from the saturation channel in HSL space.

desaturate('#4a35e8', 0.3)
function desaturate(color: string, amount: number): string
desaturate('red', 0.5); // 'hsla(0, 50%, 50%, 1)'

Parameters

color string
The input color.
amount number
The amount to desaturate, given as a decimal between 0 and 1.

Returns

string The desaturated color as an hsla string.

1.67 kB imported alone Source

adjustHue(color, degrees)

Rotates a color's hue by the given number of degrees and returns the result as an hsla string.

120°
Jump to
adjustHue('#4a35e8', 120)
function adjustHue(color: string, degrees: number): string

A hue past 360 wraps around the color wheel. A hue below 0 does not: when the color's own hue plus degrees is negative, the result has a negative hue. adjustHue('red', -120) returns hsla(-120, 100%, 50%, 1), which browsers understand but color2k cannot parse again. adjustHue('blue', -120) is fine, because blue's hue is 240.

adjustHue('red', 180); // 'hsla(180, 100%, 50%, 1)'

Parameters

color string
The input color.
degrees number
The number of degrees to rotate the hue.

Returns

string The adjusted color as an hsla string.

1.67 kB imported alone Source

complement(color)

Rotates a color's hue by 180 degrees and returns the result as an hsla string, like Sass's complement.

Half a turn round the wheel, the same as adjustHue by 180.

complement('#4a35e8')
function complement(color: string): string

Like adjustHue, the result is rounded to whole degrees and percents, so each channel can be up to 5 away from Sass's exact result. Grays have no hue and keep their color, but their channels can move by 1 from that rounding.

complement('red'); // 'hsla(180, 100%, 50%, 1)'

Parameters

color string
The input color.

Returns

string The complementary color as an hsla string.

1.69 kB imported alone Source

invert(color, weight)

Inverts a color's red, green, and blue channels, keeping its alpha, and returns the result as an rgba string.

Halfway is always gray.

invert('#4a35e8')
function invert(color: string, weight: number = 1): string

This matches Sass's invert.

weight controls how far to go toward the inverse: 1 (the default) fully inverts the color, 0 returns it unchanged, and 0.5 always gives gray. Weights outside 0 to 1 are clamped to that range. A weight that is not a finite number (NaN or Infinity) throws a RangeError.

invert('red'); // 'rgba(0, 255, 255, 1)'
invert('#336699', 0.25); // 'rgba(89, 115, 140, 1)'

Parameters

color string
The input color.
weight number = 1
How much to invert, given as a decimal between 0 and 1.

Returns

string The inverted color as an rgba string.

1.58 kB imported alone Source

opacify(color, amount)

Makes a color more opaque by increasing the alpha channel.

Your color is solid, so this starts from it at 40% and builds back up.

opacify('rgba(74, 53, 232, 0.4)', 0.3)
function opacify(color: string, amount: number): string

This is equivalent to transparentize(color, -amount).

opacify('rgba(255, 255, 255, 0.5)', 0.1); // 'rgba(255, 255, 255, 0.6)'

Parameters

color string
The input color.
amount number
The amount to increase opacity by, given as a decimal between 0 and 1.

Returns

string The more opaque color as an rgba string.

1.54 kB imported alone Source

transparentize(color, amount)

Makes a color more transparent by decreasing the alpha channel.

transparentize('#4a35e8', 0.4)
function transparentize(color: string, amount: number): string
transparentize('white', 0.1); // 'rgba(255, 255, 255, 0.9)'

Parameters

color string
The input color.
amount number
The amount to increase transparency by, given as a decimal between 0 and 1.

Returns

string The more transparent color as an rgba string.

1.53 kB imported alone Source

This section as MarkdownBack to the top

Functions

Mix Mix CSS colors and build color scales

Blend two colors, or draw a scale through as many as you like.

mix(color1, color2, weight)

Mixes two colors together using the Sass mix algorithm and returns an rgba color string.

Mix with
mix('#4a35e8', '#ff2d6f', 0.5)
function mix(color1: string, color2: string, weight: number): string
mix('red', 'blue', 0.5); // 'rgba(128, 0, 128, 1)'

Parameters

color1 string
The first color.
color2 string
The second color.
weight number
The mix weight as a decimal between 0 and 1.

Returns

string The mixed color as an rgba string.

1.63 kB imported alone Source

getScale(...colors)

Returns a scale function that interpolates through a list of colors.

Through
const scale = getScale('#4a35e8', '#e935d4', '#e94a35', '#d4e935', '#35e94a', '#35d4e9', '#4a35e8') scale(0.5)
function getScale(...colors: string[]): (n: number) => string

Pass at least two colors. With fewer there is nothing to interpolate between, and the scale has no colors to return.

The returned function accepts a decimal between 0 and 1 and returns the color at that percentage in the scale.

const scale = getScale('red', 'yellow', 'green');
console.log(scale(0)); // rgba(255, 0, 0, 1)
console.log(scale(0.5)); // rgba(255, 255, 0, 1)
console.log(scale(1)); // rgba(0, 128, 0, 1)

With a single color, the scale always returns that color.

If you'd like to limit the domain and range like chroma-js, we recommend wrapping scale again.

const _scale = getScale('red', 'yellow', 'green');
const scale = x => _scale(x / 100);

console.log(scale(0)); // rgba(255, 0, 0, 1)
console.log(scale(50)); // rgba(255, 255, 0, 1)
console.log(scale(100)); // rgba(0, 128, 0, 1)

Parameters

...colors string[]
The colors to interpolate through.

Returns

(n: number) => string A function that maps a decimal percentage to an rgba color.

1.70 kB imported alone Source

This section as MarkdownBack to the top

Functions

Contrast Readable text color and WCAG contrast

Measure how well two colors read together, and pick text that works.

getContrast(color1, color2)

Returns the contrast ratio between two colors based on the WCAG contrast ratio formula.

Aa Colors that read.

7.08:1 Passes AAA

Against
getContrast('#4a35e8', '#ffffff')
function getContrast(color1: string, color2: string): number

The ratio is between 1 and 21 for opaque, in-range colors. Alpha is ignored, and out-of-range channels such as rgb(999, 0, 0) are not clamped, so they give ratios that mean nothing.

getContrast('#444', '#fff'); // 9.739769120526205

Parameters

color1 string
The first color.
color2 string
The second color.

Returns

number The contrast ratio between the two colors.

1.58 kB imported alone Source

getLuminance(color)

Returns the relative luminance of a color using the WCAG formula.

Above 0.179, readableColor answers black.

getLuminance('#4a35e8')
function getLuminance(color: string): number
getLuminance('papayawhip'); // 0.877971001998354

Parameters

color string
The input color.

Returns

number A number between 0 for darkest black and 1 for lightest white.

1.55 kB imported alone Source

hasBadContrast(color, standard, background)

Returns whether a color fails a contrast threshold against a background.

Aa Colors that read.
standardneedsreturns
'decorative'1.5:1false
'readable'3:1false
'aa'4.5:1false
'aaa'7:1false

Your color on this background is 7.08:1.

Background
hasBadContrast('#4a35e8', 'aa', '#ffffff')
function hasBadContrast(color: string, standard: 'decorative' | 'readable' | 'aa' | 'aaa' = 'aa', background: string = '#fff'): boolean

The standards and the minimum contrast ratio each one needs are decorative (1.5), readable (3), aa (4.5), and aaa (7). By default the color is checked against aa on a white (#fff) background.

hasBadContrast('red', 'aa'); // true

Parameters

color string
The foreground color.
standard 'decorative' | 'readable' | 'aa' | 'aaa' = 'aa'
The contrast standard to test against. Defaults to aa.
background string = '#fff'
The background color. Defaults to #fff.

Returns

boolean true when the contrast ratio is below the selected standard.

1.65 kB imported alone Source

readableColor(color)

Returns black or white, whichever has better contrast against the given color.

Label

The same hue from light to dark. The label flips where black stops reading.

readableColor('#4a35e8')
function readableColor(color: string): string
readableColor('white'); // '#000'

Parameters

color string
The background color.

Returns

string #000 or #fff.

1.58 kB imported alone Source

readableColorIsBlack(color)

Returns whether black is the more readable color to place on top of the input color.

truetruetruefalsefalsefalsefalsefalsefalsefalse

The same ramp, with the boolean each step returns.

readableColorIsBlack('#4a35e8')
function readableColorIsBlack(color: string): boolean

This is the boolean form of readableColor.

readableColorIsBlack('white'); // true

Parameters

color string
The background color.

Returns

boolean true when black is the more readable foreground color.

1.57 kB imported alone Source

This section as MarkdownBack to the top

Functions

Utilities Clamp a number and catch a color that will not parse

The clamp color2k uses inside, and the error it throws when it cannot read a color.

guard(low, high, value)

Clamps a number between a lower and upper bound.

Past the rail. The dot is what guard hands back.

guard(0, 1, 1.3)
function guard(low: number, high: number, value: number): number
guard(0, 1, 2); // 1

Parameters

low number
The lower bound.
high number
The upper bound.
value number
The number to clamp.

Returns

number The clamped number.

227 B imported alone Source

ColorError

Error thrown when color2k cannot parse an input color.

Try

Thrown, and caught by the try.

parseToRgba('not-a-color')
class ColorError extends Error
new ColorError('nope').message; // 'Failed to parse color: "nope"'

Constructor parameters

color string
The color value that failed to parse.

249 B imported alone Source

This section as MarkdownBack to the top

Guides

Themes A light and dark theme from one color

Three builders, each about 35 lines of color2k. Change the color mode by the logo and they rebuild.

Pick a color and let color2k work out the rest. Each of these three builders takes a color and returns the same fourteen tokens, for light or dark.

Each one also looks at what you gave it and makes a few decisions. It returns those too, as why.

Soft

Soft is a pastel wash. It tames a loud color with desaturate and lifts a nearly gray one with saturate. Once it is calmed, your color becomes the button, unless the label would not read on it or the button would melt into the page. Then the button gets a pastel of the same hue.

NewMuted text

Soft

Body text sits on the page color, and this is a link.

Text on a card

you@studio.com

What it decided about your color

  • Your color is already gentle, so its saturation is left alone.

    const calm = vivid ? desaturate(solid, 0.2) : faint ? saturate(solid, 0.3) : solid;
  • A label would not read on your color, or it would melt into the page, so the button gets a pastel of the same hue.

    const clash = hasBadContrast(onAccent, 'aa', calm) || hasBadContrast(calm, 'decorative', bg);

Text 14.3:1 Button 5.4:1 Chip 11.2:1

The fourteen tokens it returned

softTheme('#4a35e8')
The whole builder, 36 lines
function softTheme(color, dark = false) {
  // A see-through pick is flattened onto the page first, the way it would look.
  const solid = toHex(mix(dark ? '#000' : '#fff', toHex(color).slice(0, 7), parseToRgba(color)[3]));
  const [, saturation] = parseToHsla(solid);
  const vivid = saturation > 0.8;
  const faint = saturation < 0.35;
  // Tame a loud color and lift a quiet one, so the wash is always gentle.
  const calm = vivid ? desaturate(solid, 0.2) : faint ? saturate(solid, 0.3) : solid;
  const [hue, chroma] = parseToHsla(calm);
  const tone = (lightness, scale = 1) => toHex(hsla(hue, chroma * scale, lightness, 1));
  const bg = dark ? tone(0.13, 0.4) : tone(0.97);
  const text = dark ? tone(0.93, 0.7) : tone(0.2, 0.6);
  const onAccent = dark ? tone(0.15, 0.5) : text;
  // The button is your color, unless its label would not read on it or the
  // button would melt into the page.
  const clash = hasBadContrast(onAccent, 'aa', calm) || hasBadContrast(calm, 'decorative', bg);
  const accent = clash ? tone(dark ? 0.78 : 0.74) : toHex(calm);

  return {
    bg,
    surface: dark ? tone(0.18, 0.4) : '#ffffff',
    border: dark ? tone(0.28, 0.4) : tone(0.9, 0.8),
    text,
    muted: dark ? tone(0.74, 0.5) : tone(0.3, 0.5),
    onSurface: text,
    accent,
    accentHover: toHex(mix(accent, readableColor(onAccent), 0.15)),
    onAccent,
    soft: toHex(mix(accent, bg, 0.72)),
    onSoft: text,
    ring: transparentize(accent, 0.45),
    extra: toHex(adjustHue(accent, 40)),
    shadow: transparentize(accent, 0.5),
    why: { vivid, faint, clash },
  };
}

Serious

Serious drains the color out. The page is built from grays that keep 8% of the hue. Your color is the link and the button, so it has to read on the page. If hasBadContrast says it doesn't, the theme darkens it a step at a time until it does. Then readableColorIsBlack picks the button label.

NewMuted text

Serious

Body text sits on the page color, and this is a link.

Text on a card

you@studio.com

What it decided about your color

  • Your color already reads on this page, so it is the link and the button with no nudge.

    const weak = hasBadContrast(solid, 'aa', bg);
  • The button came out dark, so its label is white.

    const darkLabel = readableColorIsBlack(accent);

Text 15.8:1 Button 7.1:1 Chip 12.6:1

The fourteen tokens it returned

seriousTheme('#4a35e8')
The whole builder, 34 lines
function seriousTheme(color, dark = false) {
  // A see-through pick is flattened onto the page first, the way it would look.
  const solid = toHex(mix(dark ? '#000' : '#fff', toHex(color).slice(0, 7), parseToRgba(color)[3]));
  const [hue] = parseToHsla(solid);
  const gray = (lightness) => toHex(desaturate(hsla(hue, 1, lightness, 1), 0.92));
  const bg = dark ? gray(0.1) : gray(0.98);
  const text = dark ? gray(0.93) : gray(0.13);
  // Links are set in your color, so it has to read on the page.
  const weak = hasBadContrast(solid, 'aa', bg);
  let accent = solid;
  for (let i = 0; i < 50 && hasBadContrast(accent, 'aa', bg); i++) {
    accent = toHex(dark ? lighten(accent, 0.02) : darken(accent, 0.02));
  }
  const darkLabel = readableColorIsBlack(accent);
  const onAccent = darkLabel ? '#000' : '#fff';

  return {
    bg,
    surface: dark ? gray(0.14) : '#ffffff',
    border: dark ? gray(0.24) : gray(0.88),
    text,
    muted: dark ? gray(0.68) : gray(0.4),
    onSurface: text,
    accent,
    accentHover: toHex(mix(accent, readableColor(onAccent), 0.15)),
    onAccent,
    soft: toHex(mix(accent, bg, 0.86)),
    onSoft: text,
    ring: transparentize(accent, 0.6),
    extra: dark ? gray(0.3) : gray(0.8),
    shadow: transparentize(text, 0.92),
    why: { weak, darkLabel },
  };
}

Bold

Bold uses your color as the page, after turning a muted one up with saturate. A light page gets black text, black cards and hard black shadows. A dark page gets white text and cards tinted from the page with lighten. The button is the hue next door, 40 degrees along the wheel, unless it would disappear on the card. Then it falls back to black or white.

NewMuted text

Bold

Body text sits on the page color, and this is a link.

Text on a card

you@studio.com

What it decided about your color

  • Your color is already vivid, so it is used at full strength.

    const brand = toHex(dull ? saturate(solid, 0.35) : solid);
  • The page came out dark, so text goes white and the card is a lighter tint of the page.

    const tinted = !light;
  • The hue next door would disappear on the card, so the button falls back to black or white.

    const accent = lost ? readableColor(surface) : neighbor;

Text 7.1:1 Button 21:1 Chip 7.1:1

The fourteen tokens it returned

boldTheme('#4a35e8')
The whole builder, 37 lines
function boldTheme(color, dark = false) {
  // A see-through pick is flattened onto the page first, the way it would look.
  const solid = toHex(mix(dark ? '#000' : '#fff', toHex(color).slice(0, 7), parseToRgba(color)[3]));
  const [, saturation] = parseToHsla(solid);
  const dull = saturation < 0.5;
  // Bold needs volume, so a muted color is turned up first.
  const brand = toHex(dull ? saturate(solid, 0.35) : solid);
  const bg = dark ? toHex(mix(brand, 'black', 0.82)) : brand;
  const light = readableColorIsBlack(bg);
  const text = light ? '#000' : '#fff';
  // A light page gets black cards. A dark page gets cards tinted from it.
  const tinted = !light;
  const surface = tinted ? toHex(lighten(bg, 0.14)) : '#000';
  const neighbor = toHex(adjustHue(brand, 40));
  // The button is the hue next door, unless it would disappear on the card.
  const lost = hasBadContrast(neighbor, 'readable', surface);
  const accent = lost ? readableColor(surface) : neighbor;
  const onAccent = readableColor(accent);

  return {
    bg,
    surface,
    border: text,
    text,
    muted: text,
    onSurface: readableColor(surface),
    accent,
    accentHover: toHex(mix(accent, readableColor(onAccent), 0.15)),
    onAccent,
    soft: text,
    onSoft: bg,
    ring: transparentize(accent, 0.4),
    extra: toHex(adjustHue(brand, 340)),
    shadow: light ? '#000' : accent,
    why: { dull, light, tinted, lost },
  };
}

The text pairs in all three (text on the page, text on a card, the button label, the chip, and the Serious link) hold WCAG AA for any color you pass, see-through ones included. The build sweeps about 1,300 colors through each one to check.

A theme is a plain object of strings, so putting it on the page is a loop:

const tokens = { bg: '#fdf1f6', text: '#471f2e', accent: '#f584ae' };

for (const [name, value] of Object.entries(tokens)) {
  globalThis.document?.documentElement.style.setProperty(`--${name}`, value);
}

This section as MarkdownBack to the top

Guides

Recipes Hover states, palettes and contrast fixes

Everyday color jobs, each done in a few calls.

Every example here runs against the built package in CI. The picture under each one is drawn from what that code returned, so the two can't disagree.

Hover, active and focus states#

Work them out from the brand color so you never hard-code them again.

import { darken, readableColor, transparentize } from 'color2k';

function createTheme(brand) {
  return {
    brand,
    brandHover: darken(brand, 0.06),
    brandActive: darken(brand, 0.12),
    brandSubtle: transparentize(brand, 0.88),
    focusRing: transparentize(brand, 0.6),
    onBrand: readableColor(brand),
  };
}

const theme = createTheme('rebeccapurple');

theme.brandHover; // 'hsla(270, 50%, 34%, 1)'
theme.brandSubtle; // 'rgba(102, 51, 153, 0.12)'
theme.onBrand; // '#fff'
brandrebeccapurple brandHoverhsla(270, 50%, 34%, 1) brandActivehsla(270, 50%, 28%, 1) brandSubtlergba(102, 51, 153, 0.12) focusRingrgba(102, 51, 153, 0.4) onBrand#fff

Readable text on any background#

readableColor answers black or white. readableColorIsBlack gives you the same answer as a boolean, for when you have your own ink and paper colors.

import { readableColor, readableColorIsBlack } from 'color2k';

const backgrounds = ['gold', 'tomato', 'rebeccapurple', 'midnightblue'];

const labels = backgrounds.map((background) => ({
  background,
  color: readableColor(background),
  label: background,
}));

labels[0].color; // '#000'
labels[3].color; // '#fff'

// Use your own ink and paper colors instead of pure black and white.
const text = readableColorIsBlack('gold') ? '#1a1a1a' : '#fafafa'; // '#1a1a1a'
gold14.97:1 · AAA tomato7.13:1 · AAA rebeccapurple8.41:1 · AAA midnightblue14.85:1 · AAA

Contrast checks#

getContrast returns the WCAG contrast ratio, which runs from 1 to 21 for opaque, in-range colors. hasBadContrast compares it to a standard: 'decorative' (1.5), 'readable' (3), 'aa' (4.5, the default) or 'aaa' (7).

import { getContrast, hasBadContrast } from 'color2k';

const pairs = [
  { color: '#767676', background: 'white' },
  { color: '#999', background: 'white' },
  { color: 'gold', background: 'midnightblue' },
];

getContrast('#767676', 'white').toFixed(2); // '4.54'

hasBadContrast('#767676'); // false
hasBadContrast('#767676', 'aaa'); // true
hasBadContrast('#999'); // true
hasBadContrast('gold', 'aa', 'midnightblue'); // false
Aa Text4.54:1 · AA Aa Text2.85:1 · fails AA Aa Text10.59:1 · AAA

Both functions ignore alpha and do not clamp, so give them opaque, in-range colors. A see-through color has no contrast ratio of its own, because it depends on what is behind it. getContrast('rgb(999, 0, 0)', 'black') is a meaningless 103.

To nudge a color until it passes AA, flatten it onto the background first. Then a see-through color is measured the way it will be seen:

import {
  darken,
  hasBadContrast,
  lighten,
  parseToRgba,
  readableColorIsBlack,
  rgba,
  toHex,
} from 'color2k';

// What `color` looks like on top of an opaque `background`.
function flatten(color, background) {
  const [red, green, blue, alpha] = parseToRgba(color);
  const under = parseToRgba(background);
  const over = (top, bottom) => top * alpha + bottom * (1 - alpha);

  return rgba(over(red, under[0]), over(green, under[1]), over(blue, under[2]), 1);
}

function accessible(color, background = '#fff') {
  // Move away from the background: darker on light, lighter on dark.
  const adjust = readableColorIsBlack(background) ? darken : lighten;
  let result = flatten(color, background);

  for (let i = 0; i < 50 && hasBadContrast(result, 'aa', background); i++) {
    result = adjust(result, 0.02);
  }

  return toHex(result);
}

const onLight = accessible('#4dabf7'); // '#0a75cd'
const onDark = accessible('#555', '#000'); // '#787878'
const fromClear = accessible('transparent'); // '#757575'
const fromGlass = accessible('rgba(77, 171, 247, 0.5)'); // '#0b75cb'
Before2.48:1 · fails AA After4.73:1 · AA Before2.82:1 · fails AA After4.76:1 · AA Transparent4.61:1 · AA Half clear4.75:1 · AA

Color scales#

getScale takes two or more colors and hands back a function. Give that function a number from 0 to 1 and you get the color at that point.

import { getScale, toHex } from 'color2k';

const heat = getScale('#2ec4b6', '#ffd60a', '#ff3b5c');

heat(0); // 'rgba(46, 196, 182, 1)'
heat(0.5); // 'rgba(255, 214, 10, 1)'
heat(0.75); // 'rgba(255, 137, 51, 1)'

const steps = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1].map((n) =>
  toHex(heat(n))
);

steps[2]; // '#97cd60'
#2ec4b6 #62c98b #97cd60 #cbd235 #ffd60a #ffaf1e #ff8933 #ff6248 #ff3b5c

Tints and shades#

mix blends two colors. A weight of 0 is all the first color and 1 is all the second.

import { mix, toHex } from 'color2k';

const base = 'rebeccapurple';
const tint = toHex(mix(base, 'white', 0.8)); // '#e0d6eb'
const shade = toHex(mix(base, 'black', 0.4)); // '#3d1f5c'
tint#e0d6eb baserebeccapurple shade#3d1f5c

Tailwind palette#

One color in, a 50 to 950 palette out. Use it in a Tailwind config or paste it into @theme.

import { getScale, toHex } from 'color2k';

function palette(color) {
  const scale = getScale('white', color, 'black');
  const steps = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];

  return Object.fromEntries(
    steps.map((step) => [step, toHex(scale(step / 1000))])
  );
}

const brand = palette('#6d28d9');

brand[100]; // '#e2d4f7'
brand[500]; // '#6d28d9'
brand[900]; // '#16082b'

// Tailwind 3: tailwind.config.js
const config = { theme: { extend: { colors: { brand } } } };

// Tailwind 4: paste into `@theme { ... }`
const variables = Object.entries(brand)
  .map(([step, hex]) => `--color-brand-${step}: ${hex};`)
  .join('\n');
50#f0eafb 100#e2d4f7 200#c5a9f0 300#a77ee8 400#8a53e1 500#6d28d9 600#5720ae 700#411882 800#2c1057 900#16082b 950#0b0416

CSS-in-JS#

This is what color2k was written for. The functions that adjust, mix and convert colors return plain CSS strings, so they drop straight into a template.

import styled from 'styled-components';
import { darken, readableColor, transparentize } from 'color2k';

const Button = styled.button`
  background: ${(props) => props.$color};
  color: ${(props) => readableColor(props.$color)};

  &:hover {
    background: ${(props) => darken(props.$color, 0.08)};
  }

  &:focus-visible {
    box-shadow: 0 0 0 3px ${(props) => transparentize(props.$color, 0.6)};
  }
`;

const save = <Button $color="#b3261e">Save</Button>;
Savedefault · 6.54:1 · AA Savehover · 8.81:1 · AAA Savefocus · 6.54:1 · AA

React#

import { useMemo } from 'react';
import { readableColor, transparentize } from 'color2k';

function Tag({ color, children }) {
  const style = useMemo(
    () => ({
      background: color,
      color: readableColor(color),
      boxShadow: `0 0 0 4px ${transparentize(color, 0.8)}`,
    }),
    [color]
  );

  return <span style={style}>{children}</span>;
}

const tags = [
  <Tag color="tomato">New</Tag>,
  <Tag color="gold">Sale</Tag>,
  <Tag color="midnightblue">Pro</Tag>,
];
New7.13:1 · AAA Sale14.97:1 · AAA Pro14.85:1 · AAA

Convert between formats#

import { parseToHsla, parseToRgba, toHex, toHsla, toRgba } from 'color2k';

const hex = toHex('hsl(210, 100%, 50%)'); // '#0080ff'
const rgb = toRgba(hex); // 'rgba(0, 128, 255, 1)'
const hsl = toHsla(hex); // 'hsla(210, 100%, 50%, 1)'

// Need the numbers? Parse to a tuple.
parseToRgba('#0080ff80'); // [0, 128, 255, 0.5019607843137255]
parseToHsla('tomato'); // [9.130434782608695, 1, 0.6392156862745098, 1]
hex#0080ff rgbrgba(0, 128, 255, 1) hslhsla(210, 100%, 50%, 1)

Going the other way, rgba and hsla build a color string from numbers:

import { hsla, rgba } from 'color2k';

const glass = rgba(0, 128, 255, 0.5); // 'rgba(0, 128, 255, 0.5)'
const sky = hsla(210, 1, 0.5, 1); // 'hsla(210, 100%, 50%, 1)'
glassrgba(0, 128, 255, 0.5) skyhsla(210, 100%, 50%, 1)

Check what color2k accepts#

color2k throws a ColorError when it can't parse a string, so a try tells you whether it will take one:

import { ColorError, parseToRgba } from 'color2k';

function canParse(value) {
  try {
    parseToRgba(value);
    return true;
  } catch (error) {
    if (error instanceof ColorError) return false;
    throw error;
  }
}

const inputs = ['#0d6efd', 'rgb(13, 110, 253)', 'rgb(13 110 253)', '#12345'];
const results = inputs.map((input) => [input, canParse(input)]);

canParse('#0d6efd'); // true
canParse('rgb(13 110 253)'); // false

// Loose: the shape is checked, the numbers are not.
canParse('rgb(999, 0, 0)'); // true
#0d6efd rgb(13, 110, 253) rgb(13 110 253) #12345

Don't use this as a CSS validator. The parser is small and loose on purpose:

  • Channel and alpha values are not range-checked. rgb(999, 0, 0) parses as it is written. An alpha that is not a number, such as rgba(1, 2, 3, .), does throw a ColorError.
  • Named colors are stored as hashes to save bytes, so about 3% of made-up words are accepted as if they were a color name.

If you need real validation, do it with your own rules or an allow-list before calling color2k. CSS.supports('color', value) won't do it either. Browsers accept forms color2k rejects, such as rgb(13 110 253), so a string can pass there and still throw here.

Invert and complement#

import { complement, invert } from 'color2k';

const original = '#0d6efd';
const inverted = invert(original); // 'rgba(242, 145, 2, 1)'

// The opposite side of the color wheel.
const opposite = complement(original); // 'hsla(36, 98%, 52%, 1)'

// Part of the way there. Halfway is always gray.
invert(original, 0.5); // 'rgba(128, 128, 128, 1)'
original#0d6efd invertedrgba(242, 145, 2, 1) oppositehsla(36, 98%, 52%, 1)

This section as MarkdownBack to the top

Reference

Supported colors Supported CSS color formats

What color2k reads and what it hands back.

color2k works in sRGB and reads the color syntax every browser has understood for years.

Input Examples
Hex #f00, #f008, #ff0000, #ff000080
rgb() and rgba() with commas rgb(255, 0, 0), rgba(255, 0, 0, 0.5)
hsl() and hsla() with commas hsl(0, 100%, 50%), hsla(0, 100%, 50%, 0.5)
Named colors, in any letter case red, rebeccapurple, PapayaWhip
transparent transparent

Whitespace around a color is ignored. A string in none of these forms throws a ColorError, with two caveats. About 3% of made-up names are read as some color, and the numbers inside rgb() are not range-checked or clamped. See Check what color2k accepts.

Output Returned by
hsla() string darken, lighten, saturate, desaturate, adjustHue, toHsla, hsla
rgba() string transparentize, opacify, mix, toRgba, rgba, and the function getScale returns
Hex string toHex
'#000' or '#fff' readableColor

When the input is a well-formed color, you can pass these strings back in, so wrap one in toHex, toRgba or toHsla to get the format you want. There is one exception, under Known edges: an adjustHue result with a negative hue. The other functions return numbers, tuples or booleans.

Not supported yet:

  • Space-separated syntax such as rgb(255 0 0 / 50%) and hsl(0deg 100% 50%).
  • Percentages for alpha or for rgb() channels, such as rgba(255, 0, 0, 50%).
  • hwb(), lab(), lch(), oklab(), oklch() and color().

Known edges#

  • hsla() output is rounded to whole degrees and percents, so a trip to HSL and back can move a channel by a step or two. toHex(lighten('#ffb537', 0)) is #ffb638. Keep the original string when you need the exact color back.
  • adjustHue does not wrap a hue that goes below 0. When the color's own hue plus the degrees is negative, the result has a negative hue: adjustHue('red', -120) is hsla(-120, 100%, 50%, 1). Browsers accept that, but color2k throws a ColorError if you pass it back in. adjustHue('blue', -120) is fine, because blue's hue is 240. This is a known bug. Until it is fixed, add 360 to a negative angle: adjustHue('red', 240).
  • Out-of-range numbers are not clamped on the way in. rgb(999, 0, 0) parses as written, and getContrast or getLuminance on it return numbers outside their normal range.
  • Contrast functions ignore alpha. Flatten a see-through color onto its background first, as the accessible recipe does.
  • An alpha that is not a number throws. toRgba('rgba(1, 2, 3, .)') throws a ColorError.
  • mix always returns an rgba() string, even at the ends. mix('red', 'blue', 0) is 'rgba(255, 0, 0, 1)', not 'red'.
  • getScale returns a function, not a list of colors. Call it with numbers from 0 to 1 to get your steps.

This section as MarkdownBack to the top

Reference

Size Bundle size, next to TinyColor and Polished

color2k is 2,483 bytes, minified and gzipped. That is every function on this page. Import six common ones and you ship 2,050 bytes.

≈2 kB, a typical import

≈2 kB, a typical import

Tap or hover a tile to read it.

A typical import (darken, lighten, mix, readableColor, toHex, transparentize), 1,982 BWhat tree shaking drops

One tile for each source file, sized by the gzipped bytes it adds to the bundle. The filled tiles are the files that stay after tree shaking when an app imports darken, lighten, mix, readableColor, toHex, transparentize. Inside the full bundle those tiles add up to 1,982 bytes. Bundled on their own, the same six imports come to 2,050 bytes, because the bundle then needs its own export list and gzip has less to share.

The same numbers as a table
FileGzipped size it addsKept by the six imports
parseToRgba.ts754 BYes
named colors561 BYes
export list200 BNo
parseToHsla.ts120 BYes
mix.ts104 BYes
getLuminance.ts85 BYes
invert.ts72 BNo
hsla.ts71 BYes
getScale.ts68 BNo
toHex.ts68 BYes
guard.ts66 BYes
ColorError.ts61 BYes
hasBadContrast.ts61 BNo
getContrast.ts29 BNo
rgba.ts29 BYes
adjustHue.ts21 BNo
transparentize.ts16 BYes
readableColor.ts14 BYes
complement.ts12 BNo
lighten.ts12 BYes
readableColorIsBlack.ts12 BYes
toRgba.ts10 BNo
darken.ts9 BYes
toHsla.ts8 BNo
desaturate.ts7 BNo
saturate.ts7 BNo
opacify.ts6 BNo

How it stays small#

color2k is boring on purpose. Each function takes a string and returns a string. There is nothing to configure and nothing to chain. The one clever thing in here is the packed table of color names, which costs 561 bytes. The rest is plain code written with care, so you can drop it into anything.

  • It does less. color2k has the color functions apps use every day, in sRGB, and stops there.
  • Two output formats. Results come back as rgba() or hsla() strings, which every browser reads, and toHex covers the rest. That skips the code other libraries spend on optional alpha channels and extra color models.
  • A squeezed color-name table. The 148 CSS color names are stored as one hashed string of 740 characters. A plain lookup object would be several times that.
  • One function per file. Nothing is shared but the parser, so your bundler drops whatever you don't import.

Missing something you need? Open an issue.

What it costs#

All 25 exports together are 2.48 kB, minified and gzipped. Import one and this is what lands in your bundle:

Import Alone Import Alone Import Alone
getScale 1.70 kB mix 1.63 kB transparentize 1.53 kB
complement 1.69 kB getContrast 1.58 kB toRgba 1.52 kB
lighten 1.68 kB invert 1.58 kB parseToRgba 1.46 kB
saturate 1.68 kB parseToHsla 1.58 kB hsla 312 B
desaturate 1.67 kB readableColor 1.58 kB rgba 283 B
adjustHue 1.67 kB readableColorIsBlack 1.57 kB ColorError 249 B
darken 1.67 kB getLuminance 1.55 kB guard 227 B
toHsla 1.66 kB opacify 1.54 kB
hasBadContrast 1.65 kB toHex 1.54 kB

The parser is about 1.5 kB and nearly every function needs it. So the first import costs the most, and each one after it adds very little. scripts/sizes.js measures these with Rollup, Terser and gzip, and CI fails if they change without the table.

Next to the others#

Library Size (min + gzip)
chroma-js 16.7 kB
polished 11.6 kB
color 8.5 kB
tinycolor2 5.4 kB
colord with the names, mix and a11y plugins 4.7 to 5.0 kB
color2k 2.5 kB

The single figures come from Bundlephobia, November 2026. colord's core is 2.3 kB without named colors, mixing or contrast checks, so its row is measured with the plugins that cover what color2k does. Bundled the way scripts/sizes.js measures color2k (Rollup, Terser with two passes, gzip at level 9), colord 2.14.0 with those three plugins is 4.86 kB. Other minifiers put it between 4.7 and 5.0 kB.

  • chroma-js16.7 kB
  • polished11.6 kB
  • color8.5 kB
  • tinycolor25.4 kB
  • colord with the names, mix and a11y plugins5.0 kB
  • color2k2.5 kB

An alternative to TinyColor and Polished#

color2k covers the everyday calls of both. Three things change when you move over. You import functions by name, the color comes first, and amounts are decimals from 0 to 1.

In tinycolor2, amounts run from 0 to 100 and calls chain off an object:

import { darken, getContrast, mix, toHex } from 'color2k';

// tinycolor('#0d6efd').darken(10).toHexString()
toHex(darken('#0d6efd', 0.1)); // '#0256d4'

// tinycolor.mix('gold', 'tomato', 25).toHexString()
toHex(mix('gold', 'tomato', 0.25)); // '#ffba12'

// tinycolor.readability('#0d6efd', '#fff')
getContrast('#0d6efd', '#fff'); // 4.500782787406787

In polished, the amount comes first and the color last:

import { darken, mix, transparentize } from 'color2k';

// darken(0.1, '#0d6efd')
darken('#0d6efd', 0.1); // 'hsla(216, 98%, 42%, 1)'

// mix(0.75, 'gold', 'tomato')
// In polished the weight is the share of the first color. Here it is the second.
mix('gold', 'tomato', 0.25); // 'rgba(255, 186, 18, 1)'

// transparentize(0.5, '#0d6efd')
transparentize('#0d6efd', 0.5); // 'rgba(13, 110, 253, 0.5)'

Both of them return hex for a solid color. color2k returns hsla() and rgba() strings, so wrap a result in toHex when you need hex. HSL results are rounded to whole percents, so that hex can sit one step away from theirs in a channel.

This section as MarkdownBack to the top

Reference

Project Credits, contributing and releases

The people behind color2k, how to help, and how it ships.

Credits#

color2k owes a lot to polished and Sass. Much of the implementation is copied from polished.

Thanks to everyone who has pitched in:

See everyone on the contributors graph.

Contributing#

Issues and pull requests are welcome. Clone the repo and run npm ci, then npm run check runs everything CI does. Each function is one small file in src with its test next to it, so most fixes touch two files.

CONTRIBUTING.md gets you set up, and AGENTS.md has the same rules for coding agents.

Trust and publishing#

  • No runtime dependencies.
  • The published package holds dist, README.md, LICENSE and package.json.
  • Releases go out from GitHub Actions with npm provenance, through trusted publishing.
  • The README, the website and the llms files are built from the JSDoc in src. CI fails if they drift.
  • Found a security problem? SECURITY.md says how to report it.

For AI agents#

If you're a model, or you're pointing one at this library, the docs come as plain Markdown:

  • color2k.com/llms.txt is a short index in the llms.txt format.
  • color2k.com/llms-full.txt has the rules below, the quickstart, every function, the supported colors and the recipes in one file, with each recipe's result written out as text. The theme builders, the size tables and the project notes are linked from it as files of their own.

Both are built from this README and the JSDoc in src. The same JSDoc ships in the type definitions, so it shows up in your editor. These are the rules that matter when you write code with color2k:

  • Install with npm i color2k. Use named imports: import { darken, toHex } from 'color2k'. There is no default export and no chaining.
  • Colors go in as CSS strings, and functions that produce a color return a CSS string. Inputs can be hex (3, 4, 6 or 8 digits), comma-separated rgb(), rgba(), hsl() or hsla(), a named color, or transparent.
  • Amounts are decimals from 0 to 1 and are absolute. darken(color, 0.1) lowers lightness by 10 percentage points. It is not a 10% relative change.
  • darken, lighten, saturate, desaturate and adjustHue return hsla() strings. transparentize, opacify and mix return rgba() strings, and so does the function getScale gives you. Wrap a result in toHex when you need hex.
  • mix(color1, color2, weight): weight 0 gives color1 and weight 1 gives color2, always as an rgba() string.
  • getScale('red', 'yellow', 'green') takes colors as separate arguments, not an array, and returns a function, not a color: call it with a number from 0 to 1.
  • readableColor(background) returns '#000' or '#fff'. hasBadContrast(color, standard = 'aa', background = '#fff') returns true when contrast is too low.
  • A string color2k can't parse throws a ColorError. Space-separated rgb(0 0 0 / 50%), percentage alpha, oklch(), lab() and color() are not supported.
  • Parsing is loose and is not validation: rgb(999, 0, 0) is accepted as written and not clamped, and about 3% of made-up color names parse as some color. Validate user input yourself before passing it in (CSS.supports is not equivalent: it accepts forms color2k rejects).
  • getContrast, hasBadContrast and readableColor ignore alpha. Flatten a see-through color onto its background before measuring.
  • adjustHue does not wrap hues below 0. If the color's hue plus the degrees is negative (adjustHue('red', -120)), the result is hsla(-120, ...), which color2k throws on if you pass it back in (a known bug). Add 360 to a negative angle to avoid it.
  • sRGB only. There are no CMYK, LAB or wide-gamut conversions.

This section as MarkdownBack to the top