While exploring the idea of using gradients for a project, I began looking into what makes gradients feel more natural.
Gradients are everywhere in modern design, yet most of them share a common flaw: they don't look natural. Those muddy brown patches between complementary colors, the visible kinks at every color stop.
The problem is how we typically create gradients. By default, CSS interpolates linearly in sRGB (Standard RGB), kept for backwards compatibility. This creates a mismatch between how computers calculate color changes and how humans actually perceive them. CSS Color 4 lets you pick another space (in oklab), which helps with muddy colors but not with kinks, since those come from the interpolation itself.
By combining spline interpolation with perceptually uniform color, we can create gradients that look smooth. Here's how we can «fix» that.
Problem
When you create a linear gradient by evenly spacing colors, the result often shows unexpected color transitions. Here's an example of such a linear gradient:
Linear gradient with red, green, and blue color stops
The transitions look uneven. This approach has two main issues:
- Linear interpolation changes direction abruptly at each color stop, producing a visible kink and a less smooth gradient.
- The sRGB color space is neither linear nor perceptually uniform, leading to unexpected «muddy» or «washed» colors during interpolation.
The first is solved by the interpolation method, the second by the color space.
Spline Interpolation
To remove the kinks, linear interpolation isn't enough. It's fast and easy to implement, but it is only continuous: the slope jumps at every data point. A spline passes through the same points with a continuous tangent.1
In this demo, linear interpolation connects data points with straight segments that form sharp corners. The Catmull-Rom Spline generates a curve through the same points that bends smoothly at each of them, which is what a gradient needs.
Catmull-Rom spline can overshoot or undershoot its control points, so interpolated colors can leave the sRGB gamut. Clamping channels fixes the range but shifts hue. Reducing chroma until the color fits does not.
Perceptual Color Spaces
The human visual system doesn't perceive color changes uniformly across all hues, brightness levels, or saturation values.
For example, our perception of brightness follows a non-linear curve: we are more sensitive to changes in darker tones than in brighter ones, even when the mathematical differences are identical.
This is why RGB, despite being computationally convenient, often produces unexpected results when interpolating between colors. Equal steps in RGB values don't correspond to equal steps in visual perception, which leads to the «muddy» or «washed out» intermediate colors we see in traditional gradients.
HSL doesn't fix this. At the same L and S, yellow looks much lighter than blue, while in OkLCh the perceived lightness stays constant along the hue axis:
HSL vs OkLChPerceptually uniform color spaces organize colors according to how humans actually see them. In these spaces, equal numerical distances correspond to roughly equal perceived differences. When we interpolate between colors in them, each step of the gradient is a consistent visual change, resulting in more even transitions.
Several are available: CIELAB (), Oklab, , and XYB. Linear RGB is not one of them: it is physically linear, but not perceptual.
I use Oklab. It is cheap to compute and, unlike CIELAB, keeps hue stable as lightness changes, notably in blues. Its cylindrical form, OkLCh, is convenient for choosing colors.
For a more detailed explanation of color spaces and perceptual uniformity, I recommend the «What is a color space?» chapter from «Making Software» by Dan Hollick. It covers color theory with clear explanations.
Implementation
Here is a Python implementation using coloraide. It creates three random colors in OkLCh within ranges of lightness and chroma, converts them to Oklab for Catmull-Rom interpolation, and writes the result to a 400×400 PNG. Out-of-gamut colors are mapped back into sRGB with fit().
from coloraide import Color
from coloraide.interpolate.catmull_rom import CatmullRom
from PIL import Image
class Custom(Color): ...
Custom.register(CatmullRom())
colors = [
Custom.random('oklch', limits=[(0.5, 0.75), (0.05, 0.2)]).to_string()
for _ in range(3)
]
interpolator = Custom.interpolate(colors, space='oklab', method='catrom')
width, height = 400, 400
image = Image.new('RGB', (width, height))
pixels = image.load()
for y in range(height):
progress = y / (height - 1)
color = interpolator(progress).convert('srgb').fit().coords()
r, g, b = [round(c * 255) for c in color[:3]]
for x in range(width):
pixels[x, y] = (r, g, b) # type: ignore
image.save('gradient.png', format='PNG')The results were good overall, but they still felt somewhat synthetic. The random color generation sometimes produced pairings that were valid but not cohesive.
This is why we need a more controlled way to generate color stops, one that keeps neighbouring colors related.
Smoother Color Samples
Instead of drawing each stop independently, we generate them as a random walk in OkLCh with a bounded step per component.
The OkLCh color space defines colors using Lightness (), Chroma (), and Hue (). The algorithm generates a sequence of colors with constrained transitions in this space.
Generate colors, each defined as , where:
To keep transitions small, limit the differences between consecutive colors:
where is the circular distance, since hue wraps around.
Process steps:
- First color (): sample , , uniformly from their ranges.
- Subsequent colors (): add a uniform perturbation within , , to the previous color. Clamp and to their ranges and wrap modulo 360.
- Converting to CSS: each color maps directly to an OkLCh string (e.g.,
oklch(75% 0.15 240)) for use in code.2
import numpy as np
def generate_colors(
n: int,
l_range: tuple[float, float] = (0.75, 0.85),
c_range: tuple[float, float] = (0.05, 0.15),
l_delta: float = 0.05,
c_delta: float = 0.03,
h_delta: float = 60.0,
seed: int | None = None,
) -> list[str]:
if n < 1:
raise ValueError("n must be positive")
rng = np.random.default_rng(seed)
l = rng.uniform(*l_range)
c = rng.uniform(*c_range)
h = rng.uniform(0, 360)
colors = []
for i in range(n):
if i:
l = float(np.clip(l + rng.uniform(-l_delta, l_delta), *l_range))
c = float(np.clip(c + rng.uniform(-c_delta, c_delta), *c_range))
h = (h + rng.uniform(-h_delta, h_delta)) % 360
colors.append(f"oklch({l * 100:.1f}% {c:.3f} {h:.1f})")
return colors
if __name__ == "__main__":
for i, color in enumerate(generate_colors(4), 1):
print(f"{i:2}: {color}")Results
The combination of controlled color sampling, Catmull-Rom spline interpolation, and the Oklab color space produces gradients with no kinks at the stops and no muddy intermediates.
By constraining the differences between consecutive color stops, we avoid jarring combinations while keeping visual interest throughout the transition.
This demo uses
mulberry32as its PRNG instead of NumPy's generator: about ten lines, a single 32-bit state, no dependencies.
Where linear sRGB interpolation produces muddy intermediates and sharp transitions, this approach preserves vibrancy and avoids the «mechanical» feel of straight segments.
The cost is a color-space conversion per sample, a four-point spline evaluation instead of a lerp, and gamut mapping.
Conclusion
Combining spline interpolation with a perceptually uniform color space gives gradients that match human visual expectations more closely. Oklab removes the muddy midpoints, the spline removes the kinks, and constraining neighbouring stops keeps the palette cohesive.
The extra cost is negligible for gradients generated once, and may matter per pixel or per frame. The output is plain CSS: sample the spline at N points and emit them as oklch() stops of a regular linear-gradient.
Footnotes
-
The approach follows the notebook «Perceptually Smooth Multi-Color Linear Gradients» by Matt DesLauriers. ↩
-
The CSS
oklch()function, e.g.oklch(75% 0.15 140), takes lightness, chroma, and hue in degrees, so the generator's output can be used in CSS as is. ↩