Skip to content

rgbToCss

Formats an RGB(A) color as a CSS rgb() value, in the modern space-separated syntax that every current browser and SVG renderer reads.

Channels are clamped to 0-255 and rounded; alpha is clamped to 0-1, rounded to 3 decimals, and left out when the color is opaque.

Available since v3.1.5

import { rgbToCss } from '@helpers4/color';
// or, from the all-in-one package (same code, one install):
import { rgbToCss } from 'helpers4/color';
rgbToCss(color: RgbColor): string
ParameterTypeDescription
colorRgbColorThe color to format. `a` defaults to 1 (opaque) when omitted.

string — rgb(r g b), or rgb(r g b / a) when translucent

The alpha is left out.

rgbToCss({ r: 255, g: 128, b: 0 }) // => 'rgb(255 128 0)'

The alpha comes after a slash.

rgbToCss({ r: 255, g: 128, b: 0, a: 0.5 }) // => 'rgb(255 128 0 / 0.5)'

An RGB(A) color with channels expressed as plain numbers, convenient for further conversion or manipulation.

interface RgbColor {
  a?: number;
  b: number;
  g: number;
  r: number;
}

View source on GitHub