Generate hexadecimal output

Choose hexadecimal only when an eight-bit sRGB value matches the consumer's storage and gamut requirements.

Use hexadecimal for systems that explicitly require compact, eight-bit sRGB. Keep native CSS output when the source space, wide gamut, or decimal precision matters.

Understand the reduction

Hexadecimal is not a neutral spelling of every color. toHex() converts to sRGB, clamps channels to its gamut, then rounds each channel to one byte.

source color -> sRGB conversion -> clamp -> 8-bit rounding -> #rrggbb
source color -> sRGB conversion -> clamp -> 8-bit rounding -> #rrggbb

Alpha adds a fourth byte at the end. It does not change the RGB reduction.

Generate opaque and translucent output

use PhpColor\Color\Color;

$opaque = Color::parse('rgb(59 130 246)');
$transparent = Color::parse('oklch(0.65 0.18 264 / 0.5)');

echo $opaque->toHex().PHP_EOL;
echo $transparent->toHex(withAlpha: true).PHP_EOL;
echo $transparent->toCss().PHP_EOL;
use PhpColor\Color\Color; $opaque = Color::parse('rgb(59 130 246)'); $transparent = Color::parse('oklch(0.65 0.18 264 / 0.5)'); echo $opaque->toHex().PHP_EOL; echo $transparent->toHex(withAlpha: true).PHP_EOL; echo $transparent->toCss().PHP_EOL;

The output is:

#3b82f6
#5588fb80
oklch(0.65 0.18 264 / 0.5)
#3b82f6 #5588fb80 oklch(0.65 0.18 264 / 0.5)

The hexadecimal value no longer records that the source used Oklch. The alpha byte 80 is 128 / 255, so its restored value is close to, but not exactly, 0.5. With alpha enabled, CSS uses #rrggbbaa, not #aarrggbb.

Avoid hexadecimal for wide-gamut identity

A Display P3 color can lie outside sRGB. Its hexadecimal output is valid CSS, but it represents the clamped sRGB result rather than the original P3 coordinates. Store native CSS or structured channels when that distinction matters.

Before using hex as a persistence format, serialize, parse, and verify the restored value against the application's tolerance. Use Preserve Display P3 in a stored CSS token when the source space must survive.

Continue with Precision and gamut, Convert HEX to RGB, or ColorInterface.