Choose black or white text

Select whichever standard text color has the stronger WCAG contrast against a known background.

Limit the candidates to the two text colors your component allows:

use PhpColor\Color\Color;
use PhpColor\Color\Contrast\ColorContrast;
use PhpColor\Color\Contrast\ContrastSolver;

$background = Color::parse('#7c3aed');
$foreground = ContrastSolver::bestOn($background, [
    Color::parse('#000000'),
    Color::parse('#ffffff'),
]);

assert('#ffffff' === $foreground->toHex());
assert(ColorContrast::calculate($foreground, $background) >= 5.69);
use PhpColor\Color\Color; use PhpColor\Color\Contrast\ColorContrast; use PhpColor\Color\Contrast\ContrastSolver; $background = Color::parse('#7c3aed'); $foreground = ContrastSolver::bestOn($background, [ Color::parse('#000000'), Color::parse('#ffffff'), ]); assert('#ffffff' === $foreground->toHex()); assert(ColorContrast::calculate($foreground, $background) >= 5.69);

bestOn() returns the candidate with the highest WCAG contrast ratio. Highest does not automatically mean sufficient, so verify the selected ratio against the requirement for the actual text.

See WCAG contrast or ContrastSolver.