hex-to-oklch

Tiny, zero-dependency hex/RGB color to OKLCH converter. Library + CLI.
Works with Node.js, Bun, Deno, and any ESM-compatible runtime.
Install
npm install hex-to-oklch
CLI
npx hex-to-oklch '#ff6600'
API
import {
ACHROMATIC_CHROMA_THRESHOLD,
formatOklch,
hexToOklch,
isAchromatic,
rgbToOklch,
} from "hex-to-oklch";
hexToOklch(hex: string, options?: HexToOklchOptions): Oklch
Convert a hex color to OKLCH. Accepts #RGB, #RGBA, #RRGGBB, #RRGGBBAA.
The # prefix is optional. Alpha is preserved as a when present in input
unless options.alpha changes behavior.
Throws on invalid input.
hexToOklch("#ff0000");
hexToOklch("#ff000080");
hexToOklch("#ff000080", { alpha: "discard" });
hexToOklch("#ff000080", { alpha: "override", value: 0.25 });
hexToOklch("#808080");
type HexToOklchOptions =
| { readonly alpha?: "preserve" }
| { readonly alpha: "discard" }
| { readonly alpha: "override"; readonly value: number };
rgbToOklch(r, g, b, alpha?): Oklch · rgbToOklch(rgb: RgbInput): Oklch
Convert raw RGB values to OKLCH. Channels are integers in [0, 255]
(clamped and rounded). Optional alpha in [0, 1].
Accepts positional arguments or a single RgbInput object.
Throws on non-finite r, g, b, or alpha.
rgbToOklch(255, 0, 0);
rgbToOklch(255, 0, 0, 0.5);
rgbToOklch({ r: 128, g: 128, b: 128 });
formatOklch(rgbToOklch(186, 218, 85));
type RgbInput = {
readonly r: number;
readonly g: number;
readonly b: number;
readonly a?: number;
};
formatOklch(oklch: Oklch): string
Format an Oklch value as a CSS oklch() string.
- Values are clamped to valid ranges.
- If
a is present, formatter emits oklch(... / a).
- Achromatic colors emit CSS
none for hue and 0 chroma.
formatOklch(hexToOklch("#ff0000"));
formatOklch(hexToOklch("#808080"));
formatOklch(hexToOklch("#ff000080"));
isAchromatic(oklch: Oklch): boolean
Return true when oklch.c <= ACHROMATIC_CHROMA_THRESHOLD.
isAchromatic(hexToOklch("#808080"));
isAchromatic(hexToOklch("#808081"));
ACHROMATIC_CHROMA_THRESHOLD
const ACHROMATIC_CHROMA_THRESHOLD = 4e-6;
Powerless-hue epsilon used for achromatic checks in this library.
See CSS Color 4 §4.4.1.
Oklch
type Oklch = {
readonly l: number;
readonly c: number;
readonly h: number;
readonly a?: number;
};