Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Change text color based on a brightness of the covered background area in HTML?
Changing text color based on the brightness of the background ensures optimal readability and contrast. This technique calculates the luminance of the background color and automatically selects either black or white text for maximum visibility.
How It Works
The brightness calculation uses the relative luminance formula that weights RGB values according to human eye sensitivity. The formula gives more weight to green (587), moderate weight to red (299), and less weight to blue (114) since our eyes are most sensitive to green light.
Syntax
The luminance calculation formula is −
var luminance = ((red * 299) + (green * 587) + (blue * 114)) / 1000;
Based on the calculated luminance value, choose text color −
var textColor = (luminance > 125) ? 'black' : 'white';
Using JavaScript with Random Colors
Following example demonstrates automatic text color adjustment with randomly changing background colors −
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Text Color Based on Background</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
#box {
width: 300px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
font-weight: bold;
border: 2px solid #333;
transition: all 0.3s ease;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<div id="box">Demo Text</div>
<p>The background color changes every second, and text color adjusts automatically.</p>
<script>
var rgb = [255, 0, 0];
setInterval(display, 1000);
function display() {
rgb[0] = Math.round(Math.random() * 255);
rgb[1] = Math.round(Math.random() * 255);
rgb[2] = Math.round(Math.random() * 255);
// Calculate luminance using weighted formula
var luminance = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) +
(parseInt(rgb[2]) * 114)) / 1000);
// Choose text color based on luminance
var textColor = (luminance > 125) ? 'black' : 'white';
// Apply background and text colors
var backgroundColor = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
$('#box').css('color', textColor);
$('#box').css('background-color', backgroundColor);
}
</script>
</body>
</html>
The output shows a box that changes background color every second with automatically adjusted text color for optimal readability −
Demo Text (in a colored box - text color automatically switches between black and white based on background brightness)
Using Vanilla JavaScript
Following example shows the same functionality without jQuery −
<!DOCTYPE html>
<html>
<head>
<title>Vanilla JS Text Color Adjustment</title>
<style>
.color-box {
width: 250px;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
font-weight: bold;
border-radius: 8px;
margin: 10px 0;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<button onclick="changeColor()">Change Background Color</button>
<div id="colorBox" class="color-box">Click button to change</div>
<p id="colorInfo"></p>
<script>
function changeColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
// Calculate luminance
const luminance = (r * 299 + g * 587 + b * 114) / 1000;
// Determine text color
const textColor = luminance > 125 ? 'black' : 'white';
// Apply styles
const box = document.getElementById('colorBox');
box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
box.style.color = textColor;
// Display color information
document.getElementById('colorInfo').innerHTML =
`RGB: (${r}, ${g}, ${b}) | Luminance: ${Math.round(luminance)} | Text: ${textColor}`;
}
// Initialize with a random color
changeColor();
</script>
</body>
</html>
The output displays a colored box with automatically adjusted text color and shows the RGB values and calculated luminance −
[Change Background Color] Click button to change (in colored box with appropriate text color) RGB: (142, 87, 201) | Luminance: 115 | Text: white
Static Color Examples
Following example demonstrates the technique with predefined colors −
<!DOCTYPE html>
<html>
<head>
<title>Static Color Examples</title>
<style>
.example-box {
width: 200px;
height: 80px;
display: inline-block;
margin: 10px;
text-align: center;
line-height: 80px;
font-weight: bold;
border-radius: 5px;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Examples with Different Background Colors</h2>
<div id="examples"></div>
<script>
const colors = [
{name: 'Light Blue', rgb: [173, 216, 230]},
{name: 'Dark Red', rgb: [139, 0, 0]},
{name: 'Yellow', rgb: [255, 255, 0]},
{name: 'Navy', rgb: [0, 0, 128]},
{name: 'Light Gray', rgb: [211, 211, 211]},
{name: 'Purple', rgb: [128, 0, 128]}
];
const container = document.getElementById('examples');
colors.forEach(color => {
const [r, g, b] = color.rgb;
const luminance = (r * 299 + g * 587 + b * 114) / 1000;
const textColor = luminance > 125 ? 'black' : 'white';
const box = document.createElement('div');
box.className = 'example-box';
box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
box.style.color = textColor;
box.textContent = color.name;
container.appendChild(box);
});
</script>
</body>
</html>
The output shows various colored boxes, each with automatically chosen black or white text for optimal contrast −
Light Blue Yellow Light Gray (boxes with black text) Dark Red Navy Purple (boxes with white text)
Key Points
-
The luminance formula
(R×299 + G×587 + B×114)/1000reflects human eye sensitivity to different colors. -
A threshold of 125 provides good contrast in most cases. Values above 125 indicate bright backgrounds (use black text), below 125 indicate dark backgrounds (use white text).
-
This technique works with any RGB color value, whether from CSS properties, user input, or dynamically generated colors.
-
For better accessibility, consider using a slightly higher threshold (130-140) or implementing additional contrast ratio calculations following WCAG guidelines.
Conclusion
Dynamic text color adjustment based on background brightness ensures optimal readability across various color combinations. By using the relative luminance formula and a threshold value of 125, you can automatically switch between black and white text to maintain proper contrast and improve user experience.
