Using CSS Relative Color Syntax for Dynamic Color Manipulation
This article introduces CSS Relative Color syntax, explains its core transformation functions, demonstrates practical examples such as generating green text from red, creating unified button hover/active colors, and adapting text color to any background using the new color‑contrast() function.
Quick Syntax Introduction
The new CSS Relative Color feature lets you derive a new color B from an existing color A using a concise syntax. For example, you can define a variable with a base color and then transform its components with calc() expressions.
<p> CSS Relative Color </p> p {
color: rgb(255, 0, 0);
}To turn a red color into green, you can write:
p {
--color: rgb(255, 0, 0);
color: rgb(from var(--color) calc(r - 255) calc(g + 255) b); /* result = rgb(0, 255, 0) */
}The result is a green‑colored text as shown in the demo image.
Using CSS Relative Color for Unified Button States
Instead of writing three separate colors for normal, :hover , and :active states, you can store a base background color in a CSS variable and adjust its lightness for the different states:
div {
--bg: #fc0;
background: var(--bg);
transition: .3s all;
}
div:hover {
background: hsl(from var(--bg) h s calc(l * 1.2));
}
div:active {
background: hsl(from var(--bg) h s calc(l * 0.8));
}This approach automatically generates a brighter hover color and a darker active color based on the same base hue.
Adaptive Text Color Using color-contrast()
When the background color is dynamic (e.g., supplied by an API), you can let the browser choose the most readable text color by using the experimental color-contrast() function from CSS Color Module Level 6:
p {
--bg: #ffcc00;
background: var(--bg);
color: color-contrast(var(--bg) vs #fff, #000); /* picks the higher‑contrast color */
}This guarantees sufficient contrast on any background while keeping the UI consistent.
Summary
CSS Relative Color syntax gives developers powerful, pure‑CSS ways to manipulate colors without JavaScript, enabling features such as unified button state colors and automatic text‑color adaptation. The upcoming color-contrast() function further simplifies high‑contrast color selection, although it is still experimental and not yet widely supported.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.