Home >Web Front-end >CSS Tutorial >How Can We Dynamically Adapt Text Color for Optimal Visibility on Varying Backgrounds?
Dynamic Text Color Adaptation for Varying Background Brightness
In the realm of web development, ensuring optimal text visibility against different background colors is crucial. This technique aims to change a text's color or substitute it with predefined images/icons based on the average brightness of its parent element's background.
Existing Resources:
W3C Algorithm with JSFiddle Demo:
// Random color changes for demonstration setInterval(setContrast, 1000); function setContrast() { // Generate random RGB values rgb = [Math.round(Math.random() * 255), Math.round(Math.random() * 255), Math.round(Math.random() * 255)]; // Calculate brightness using W3C formula brightness = Math.round(((rgb[0] * 299) + (rgb[1] * 587) + (rgb[2] * 114)) / 1000); // Determine text color based on brightness textColour = (brightness > 125) ? 'black' : 'white'; // Apply colors to a sample element $('#bg').css('color', textColour); $('#bg').css('background-color', 'rgb(' + rgb.join(',') + ')'); }
In this example, the brightness of a randomly changing background color is calculated, and the text color is dynamically adjusted to provide optimal contrast.
If no background is defined for the parent element, the script can search through the element hierarchy to find the nearest element with a defined background. This ensures that text visibility is maintained consistently throughout the page.
The above is the detailed content of How Can We Dynamically Adapt Text Color for Optimal Visibility on Varying Backgrounds?. For more information, please follow other related articles on the PHP Chinese website!