With the new color spaces, one of the benefits that doesn’t involve digging deep into color science is for creating gradients. Interpolation is when you calculate one or more values between two known values, so if you have a gradient from red to blue, interpolation is how you calculate which colors are in the range between red and blue. When creating a linear-gradient()
or similar CSS gradients, you can use in
(for interpolation) followed by the color space of the gradient:
.hsl { background: linear-gradient(in hsl, blue, red);
}
Comparing gradients in different color spaces
We can create a quick example to compare gradients in different color spaces. In the example below, we have a gradient from blue to red in the standard RGB color space, and then we have the same gradient in different color spaces:
.rgb { background: linear-gradient(to right, blue, red);
} .hsl { background: linear-gradient(in hsl to right, blue, red);
} .lch { background: linear-gradient(in lch to right, blue, red);
} .lab { background: linear-gradient(in lab to right, blue, red);
} .oklch { background: linear-gradient(in oklch to right, blue, red);
} .oklab { background: linear-gradient(in oklab to right, blue, red);
}
This gives us a good idea of how the gradients look in different color spaces and how the interpolation works in each one:
Using hue interpolation modes in gradients
There are some interpolation modes that control the direction around the color wheel that the hue should be interpolated in color spaces with hue angles:
<div class="hsl in-function"> <p>HSL</p>
</div>
<div class="hsl-named in-function"> <p>HSL named</p>
</div> <div class="hsl-longer in-function"> <p>HSL (longer)</p>
</div>
<div class="hsl-named-longer in-function"> <p>HSL named (longer)</p>
</div> <div class="fallback"> <p>Standard fallback</p>
</div>
.hsl { background: linear-gradient( to right in hsl, hsl(39deg 100% 50%), hsl(60deg 100% 50%) );
} .hsl-named { background: linear-gradient(to right in hsl, orange, yellow);
} .hsl-longer { background: linear-gradient( to right in hsl longer hue, hsl(39deg 100% 50%), hsl(60deg 100% 50%) );
} .hsl-named-longer { background: linear-gradient(to right in hsl longer hue, orange, yellow);
} .fallback { background: linear-gradient(to right, blue, red);
}