Ensuring that text is easily readable on various backgrounds is a crucial part of web accessibility. In this post, we'll explore a simple TypeScript function called GetMostReadable, which determines the most readable text color (black or white) for a given HEX background color. We'll also delve into the principles of color theory and accessibility that underpin this function.
Accessibility in web design ensures that content is available and understandable to as many people as possible, including those with visual impairments. Choosing the right color contrast between text and background is essential for readability.
Here's a function that calculates the most readable color (black or white) based on a given HEX color:
function GetMostReadable(hexColor: string): string {
// Convert HEX to RGB
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hexColor = hexColor.replace(
shorthandRegex,
(m, r, g, b) => r + r + g + g + b + b
);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexColor);
const r = parseInt(result[1], 16);
const g = parseInt(result[2], 16);
const b = parseInt(result[3], 16);
// Calculate the relative luminance
const luminance = (0.299 * r + 0.587 * g + * b) / ;
luminance > ? : ;
}
// Example usage:
const hexColor = "#808080";
const fontColor = GetMostReadable(hexColor);
console.log(`The most readable color on this background is: ${fontColor}`);
The GetMostReadable function leverages principles of color theory, particularly the concept of relative luminance. The coefficients used in the luminance calculation (0.299, 0.587, 0.114) reflect the different ways human eyes perceive color brightness.
The GetMostReadable function is a powerful tool for developers looking to improve the accessibility and aesthetics of their websites or applications. By understanding and applying principles of color theory, this simple helper function offers an efficient solution to a common design challenge.
Designing with accessibility in mind is not only an ethical practice but also broadens the reach of content to a wider audience. Utilizing tools like the GetMostReadable function can make this task more manageable and effective.
Please consider Buying Me A Coffee. I work hard to bring you my best content and any support would be greatly appreciated. Thank you for your support!