Choosing High-Contrast Text Colour Based on Background Colour

Dec 14, 2022

Elements on the web can have background colours, and sometimes those background colours change. In certain cases, the background colour may change to a value where the existing text colour no longer has enough contrast to be distinctly visible. In such a case, you may also want to dynamically select a text (or foreground) colour that provides the highest text-to-background contrast ratio.

The following is a JavaScript method for taking a background colour as an input, and deciding on whether to use white (#ffffff) or black (#000000) text in response. This method uses the W3 sRGB equations to calculate relative luminance, then checks which value for the foreground colour (either black or white) has the highest contrast ratio.

For the best visibility on your webpages, according to the Web Content Accessibility Guidelines (WCAG), you should strive for a minimum foreground-to-background contrast ratio of 7:1, and anything below 4.5:1 is considered not enough contrast to be read easily by most people. See more at the MDN page on Color contrast.

Relative luminance of background colour:
Contrast ratio: : 1

This text should be quite visible.
Use this colour-picker to dynamically change the background colour:


JavaScript Code
function getLuminance(clr) {
  clr = clr.replace(/#/, '').match(/.{1,2}/g);
  for (let x = 0; x < clr.length; x++) {
    clr[x] = parseInt(clr[x], 16) / 255;
    clr[x] = (clr[x] <= 0.03928) ? clr[x] / 12.92 : ((clr[x] + 0.055) / 1.055) ** 2.4;
  }
  return 0.2126 * clr[0] + 0.7152 * clr[1] + 0.0722 * clr[2];
}

function chooseForeground(bkg) {
  let relativeLuminance = getLuminance(bkg);
  let chooseBlack = (relativeLuminance + 0.05) / 0.05;
  let chooseWhite = 1.05 / (relativeLuminance + 0.05);
  return (chooseBlack > chooseWhite) ? '#000000' : '#ffffff';
}

// Use
let bkgColour = '#ffffff';
let testArea = document.getElementById('testArea');
    testArea.style.backgroundColor = bkgColour;
    testArea.style.color = chooseForeground(bkgColour);

Post comment :: No Comments Yet

Create New Comment

Creating New Comment

Recent posts

  1. Dr. Presto - Now with MUSIC! Jan 2023
  2. Check if a String of Text can be Composed Entirely of Chemical Element Symbols Dec 2022
  3. Choosing High-Contrast Text Colour Based on Background Colour Dec 2022
  4. Making Parallaxed HTML5 Video Work Mar 2022
  5. activeImageMap script Jan 2020
  6. Archive