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.
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.
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.
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].
Rotates a color's hue by the given number of degrees and returns the result as an hsla string.
120°
Jump to
Your color is gray, and gray has no hue to turn.
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.
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.
Your color is gray, and gray has no opposite.
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.
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.
Returns the contrast ratio between two colors based on the WCAG contrast ratio formula.
AaColors that read.
7.08:1Passes AAA
134.5721
Against
This function ignores alpha, so your color is measured as if it were solid.
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.
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.
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.
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:1Button 7.1:1Chip 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 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.
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:1Button 21:1Chip 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:
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'
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).
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'
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.
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.
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)'
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.
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().
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.
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.
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.
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.
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.
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:
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.
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.
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.