Skip to content

Instantly share code, notes, and snippets.

@hchouhan
Created April 2, 2026 13:21
Show Gist options
  • Select an option

  • Save hchouhan/4e8a38922f49c03cd3d05e62ac585e93 to your computer and use it in GitHub Desktop.

Select an option

Save hchouhan/4e8a38922f49c03cd3d05e62ac585e93 to your computer and use it in GitHub Desktop.
PHP function to auto-pick black/white text color
<?php
/**
* Calculate optimal foreground (#ffffff or #000000) for a given hex background.
*
* Uses WCAG relative luminance; threshold where contrast with white equals
* contrast with black is approximately 0.179.
*
* @since 1.0.0
*
* @param string $hex Background color in hex format ('#abc', 'abc', '#aabbcc', 'aabbcc').
* @return string '#ffffff' or '#000000'.
*/
public function pick_on_color( $hex ) {
$hex = ltrim( trim( (string) $hex ), '#' );
if ( strlen( $hex ) === 3 ) {
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
}
if ( strlen( $hex ) !== 6 || ! ctype_xdigit( $hex ) ) {
return '#000000';
}
$r = hexdec( substr( $hex, 0, 2 ) ) / 255;
$g = hexdec( substr( $hex, 2, 2 ) ) / 255;
$b = hexdec( substr( $hex, 4, 2 ) ) / 255;
$r = ( $r <= 0.03928 ) ? ( $r / 12.92 ) : pow( ( $r + 0.055 ) / 1.055, 2.4 );
$g = ( $g <= 0.03928 ) ? ( $g / 12.92 ) : pow( ( $g + 0.055 ) / 1.055, 2.4 );
$b = ( $b <= 0.03928 ) ? ( $b / 12.92 ) : pow( ( $b + 0.055 ) / 1.055, 2.4 );
$l = ( 0.2126 * $r ) + ( 0.7152 * $g ) + ( 0.0722 * $b );
return ( $l <= 0.179 ) ? '#ffffff' : '#000000';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment