Skip to content

Instantly share code, notes, and snippets.

@Benbb96
Last active July 19, 2022 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Benbb96/e7b1ce654f616da08e61fa888e666354 to your computer and use it in GitHub Desktop.
Save Benbb96/e7b1ce654f616da08e61fa888e666354 to your computer and use it in GitHub Desktop.
Original PHP script from this stackoverflow question : https://stackoverflow.com/a/42921358/8439435 then updated to Python and following the WCAG 2.0 - G18.
BLACK_COLOR = "#000000"
WHITE_COLOR = "#FFFFFF"
def get_contrast_color(background_color: str) -> str:
"""
Util function to determine what's the best color between black or white to choose for a text
depending on the background color given in parameter.
Based on algorythm from WCAG 2.0 explained here : https://www.w3.org/TR/WCAG20-TECHS/G18.html#G18-tests
:param background_color: the background color in HEX format (eg: #9D412B)
:return: A black or a white color in HEX format
"""
def calc_luminosity_contrast(color: str) -> float:
extract_colors = (color[i:i+2] for i in range(1, len(color), 2))
colors_8bit = (int(c, 16) / 255 for c in extract_colors)
def relative_luminance(value: float) -> float:
return (value / 12.92) if value <= 0.03928 else pow((value + 0.055) / 1.055, 2.4)
red, green, blue = (relative_luminance(c) for c in colors_8bit)
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
l1 = calc_luminosity_contrast(background_color) + 0.05
l2 = calc_luminosity_contrast(BLACK_COLOR) + 0.05
contrast_ratio = l1 / l2 if l1 > l2 else l2 / l1
return BLACK_COLOR if contrast_ratio >= 4.5 else WHITE_COLOR
@fuzzbomb
Copy link

fuzzbomb commented Feb 21, 2022

Beware: the luminosity contrast algorithm used here is based on an early working draft of WCAG 2.0 techniques. The formula and required ratio changed in the final version.

@Benbb96
Copy link
Author

Benbb96 commented Jul 19, 2022

@fuzzbomb Thanks for the notice, I've updated my code !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment