
What is contrast-color()
in CSS?
The contrast-color()
function, part of CSS Color Level 5, automatically selects a color that contrasts well with a reference color, usually the background. Its main purpose is to ensure that text or UI elements remain readable, regardless of background color.
This makes it perfect for modern web design where readability and accessibility are critical.
How It Works
The contrast-color()
function takes a base color (typically the background) and generates a text color that ensures good contrast. In practice, it calculates the luminance of the base color and selects the most readable color from a list of candidates.
Example Syntax:
.element {
background: #3498db;
color: contrast-color(#3498db);
}
You can also provide a list of colors:
.card {
background: #f1c40f;
color: contrast-color(#f1c40f vs black, navy, white);
}
Benefits of contrast-color()
in CSS
Using contrast-color()
brings several advantages for web design:
- Enhanced Accessibility: Automatically ensures sufficient contrast for visually impaired users.
- Time-Saving: Eliminates manual testing of color combinations; contrast is calculated automatically.
- Adaptive Design: Ideal for websites with dynamic themes, such as dark mode and light mode. Text colors adjust based on background color.
- Visual Consistency: Keeps your design clean and professional, even when colors change dynamically.
How to Use It Today
Currently, browser support for contrast-color()
is limited, but you can replicate its behavior using JavaScript or Sass.
JavaScript Example:
<div id="box">Hello World</div>
<script>
function getContrastColor(hex) {
hex = hex.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
// Calcul de la luminance perçue
const luminance = (0.299*r + 0.587*g + 0.114*b) / 255;
return luminance > 0.5 ? '#000000' : '#ffffff';
}
const box = document.getElementById('box');
const bgColor = "#b8c7ff";
box.style.backgroundColor = bgColor;
box.style.color = getContrastColor(bgColor);
</script>
Sass Example:
@function contrast-color($color, $dark: #000000, $light: #ffffff) {
@if (lightness($color) > 50) {
@return $dark;
} @else {
@return $light;
}
}
.box {
background: #e67e22;
color: contrast-color(#e67e22);
}
Read Also : CSS @container: Truly Responsive Components with Container Queries
Conclusion
The contrast-color()
function is a powerful tool for improving readability and accessibility on modern websites.
- It simplifies contrast management.
- It’s perfect for dynamic or dark/light mode websites.
- While browser support is still limited, JavaScript and Sass provide practical alternatives.
Using contrast-color()
ensures that your web design is accessible, consistent, and professional, without extra manual work.