Skip to content
colors

toCSS

The `toCSS` function converts a HEX color into a valid CSS declaration string for a given property. It supports `hex`, `rgb`, `hsl`, `oklab`, and `oklch` output formats.

1 min read194 words

Function Signature

js

toCSS(hex: string, property?: string, format?: "hex" | "rgb" | "hsl" | "oklab" | "oklch"): string

Parameters

  • 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 via hexToRgb.
  • If format = "hsl", the HEX is converted to RGB, then HSL.
  • If format = "oklab", the HEX is converted to OKLab and emitted as oklab(...).
  • If format = "oklch", the HEX is converted to OKLCH and emitted as oklch(...).
  • 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.

Previous

generateTailwindConfig


Top eszközök

BoardlyLinksyChromoCodeHub

ReadyTools

KarrierKapcsolatEszközök
Árak7 nap ingyen
ÚtmutatókDocsBlogUpdatesLaraVault

Nyelv kiválasztása

Téma beállítása

© 2026 ReadyTools. Minden jog fenntartva.