Adjust color alpha

Set transparency explicitly without mutating the source color.

Transparent alpha 0 #7c3aed00
Translucent alpha 0.45 #7c3aed73
Opaque alpha 1 #7c3aedff

Change transparency, not color channels

The RGB channels remain 124, 58, and 237. Only alpha changes, and eight-digit hex quantizes 0.45 to 0x73.

Set alpha on an immutable color

withAlpha() returns the same concrete color type with a clamped alpha value. The original object remains opaque.

<?php

use PhpColor\Color\Color;

$source = Color::parse('#7c3aed');
$translucent = $source->withAlpha(0.45);

printf("%s\n%s\n",
    $translucent->toCss(),
    $translucent->toHex(withAlpha: true),
);

// rgb(124 58 237 / 0.45)
// #7c3aed73
use PhpColor\Color\Color; $source = Color::parse('#7c3aed'); $translucent = $source->withAlpha(0.45); printf("%s\n%s\n", $translucent->toCss(), $translucent->toHex(withAlpha: true), ); // rgb(124 58 237 / 0.45) // #7c3aed73

Choose the representation at the boundary

Alpha is stored from 0 to 1. Serialization decides how that value is rounded for CSS or storage.

CSS alphatoCss() keeps the decimal alpha value visible.
Hex alphatoHex(true) writes a quantized eighth channel pair.
ClampingValues below 0 become 0; values above 1 become 1.
No compositingChanging alpha does not resolve the color against a background.

Choose a next step

Set alpha, then verify the value you serialize