Combining currentcolor with relative color syntax
In 2024, browsers added support for using the currentcolor
keyword together with relative color syntax.
It’s common in UI design to set a background-color
based on text color.
A “ghost” button, for example, might show a low-opacity background when hovered.
That’s now easy to implement using relative color syntax.
.btn-warn {
background-color: transparent;
color: red;
&:hover {
background-color: oklch(from currentcolor l c h / 10%);
}
&:active {
background-color: oklch(from currentcolor l c h / 15%);
}
}
Here’s a badge example where infinite variations can be achieved by changing only the color
property.
<div class="badge" style="color: navy;">NEW</div>
<div class="badge" style="color: deeppink;">NEW</div>
<div class="badge" style="color: #009b92;">NEW</div>
<div class="badge" style="color: royalblue;">NEW</div>
.badge {
background-color: oklch(from currentcolor l c h / 12%);
border: solid 1px currentcolor;
}
As well as backgrounds, the combination of currentcolor
with relative color syntax could be useful for setting borders or shadows, or the fill
and stroke
color of an SVG, for instance. Relative color can be used to change more than opacity, as I’ve written about previously.
Here’s a slightly darker shade of the text color used for box-shadow
:
box-shadow: oklch(from currentcolor 25% c h / 45%) 0 1px 2px 0;