CSS Gradients
Overview
Gradients smoothly transition between two or more colors. In CSS, gradients are not treated as 'colors'—they are mathematically generated Images. Because they are images, you apply them using the background-image property (not background-color). Modern CSS supports linear, radial (circular), and conic (sweeping pie-chart) gradients, and allows for interpolating them in the modern oklch color space to prevent the 'gray dead zone' bug.
Syntax
/* 1. Linear Gradient (Direction, Color1, Color2...) */
.linear {
/* 'to right', 'to bottom right', or specific degrees '45deg' */
background-image: linear-gradient(to right, red, blue);
}
/* 2. Radial Gradient (Radiates outward from a center point) */
.radial {
background-image: radial-gradient(circle at center, yellow, orange);
}
/* 3. Conic Gradient (Sweeps around a center point like a radar or pie chart) */
.conic {
background-image: conic-gradient(red 0deg, green 180deg, blue 360deg);
}
/* 4. Hard Stops (Creating solid stripes instead of smooth blends) */
.stripes {
background-image: linear-gradient(to right, black 50%, white 50%);
}Common Pitfalls
- Applying a gradient to
background-color. It will silently fail and render nothing. Gradients are images; they belong onbackground-imageor the shorthandbackgroundproperty. - The 'Gray Dead Zone'. When you transition from green to red in the standard
srgbspace, the math forces the middle of the gradient to become a muddy, ugly gray. Modern CSS fixes this by addingin oklchto the gradient declaration.
Interview Questions
You apply the gradient to the background, and then use -webkit-background-clip: text; combined with -webkit-text-fill-color: transparent;. This clips the background image strictly to the exact shapes of the letters.
Real-World Example
Creating a beautiful, modern text gradient using the OKLCH interpolation space.
.text-gradient {
/* Modern OKLCH prevents muddy colors in the middle! */
background: linear-gradient(
to right in oklch,
oklch(70% 0.3 330), /* Pink */
oklch(70% 0.3 250) /* Blue */
);
/* Clip the background to the text */
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}Check Your Knowledge
Test your understanding of CSS Gradients with these quick questions.