Function Signature
js
toCSS(hex: string, property?: string, format?: "hex" | "rgb" | "hsl" | "oklab" | "oklch"): stringParameters
hex(string): HEX color string (e.g.,#ff6600).property(string, optional): CSS property name (e.g.,background-color,color). Defaults to"background-color".format("hex" | "rgb" | "hsl" | "oklab" | "oklch", optional): Desired output format. Defaults to"hex".
Return Value
A CSS declaration string in the form property: value; where value is expressed in the chosen format.
js
toCSS("#ff6600");
// "background-color: #ff6600;"
toCSS("#00aaff", "color", "rgb");
// "color: rgb(0, 170, 255);"
toCSS("#ff6600", "color", "oklch");
// "color: oklch(69.58% 0.2043 43.49);"Examples
js
console.log(toCSS("#ff6600"));
// background-color: #ff6600;
console.log(toCSS("#0000ff", "border-color", "hsl"));
// border-color: hsl(240 100% 50%);
console.log(toCSS("#ff6600", "color", "oklab"));
// color: oklab(0.6958 0.1482 0.1406);Implementation Details
- If
format = "hex", the HEX is lowercased and inserted directly. - If
format = "rgb", the HEX is converted to RGB viahexToRgb. - If
format = "hsl", the HEX is converted to RGB, then HSL. - If
format = "oklab", the HEX is converted to OKLab and emitted asoklab(...). - If
format = "oklch", the HEX is converted to OKLCH and emitted asoklch(...). - Throws an error if an unsupported format is provided.
Usage Notes
- Convenient for dynamically generating inline styles or CSS code snippets.
- Modern CSS color formats require browser support for OKLab or OKLCH.
- Supports any CSS property name, not limited to color-related properties.