The Background Gradient
CSS gradients allow you to create smooth, code-generated transitions between two or more colors. Although they define colors, they are technically treated as background images by the browser and are applied using the background-image property (or the background shorthand).
Since gradients are generated by code, they are perfectly scalable and load much faster than traditional image files.
Applying a Gradient
Gradients are functions of the background-image property:
selector {
background-image: linear-gradient(...);
/* OR */
background-image: radial-gradient(...);
}
1. linear-gradient(): Straight Transitions
A linear gradient transitions colors along a straight line. You must define a direction or angle, and at least two color stops.
Syntax and Direction
The direction can be set using keywords (to top, to right, to bottom left) or an angle in degrees (deg).
/* Direction keyword: transitions from left to right */
.box-1 {
background-image: linear-gradient(to right, #00C9FF, #92FE9D);
}
/* Angle: transitions diagonally from bottom-left to top-right */
.box-2 {
background-image: linear-gradient(45deg, #FF6B6B, #FFE66D);
}
2. radial-gradient(): Circular Transitions
A radial gradient transitions colors outward from a central point, radiating in a circular or elliptical shape.
Syntax and Shape
You can optionally specify the shape (circle or ellipse) and the position where the center of the gradient starts.
/* Default: transitions outward from the center (yellow) to the edge (red) */
.box-3 {
background-image: radial-gradient(circle at center, yellow, red);
}
/* Position: starts from the top-left corner */
.box-4 {
background-image: radial-gradient(at top left, #53a388, #3e5060);
}
Color Stops and Transparency
You can define color stops to control where the color transition begins and ends, using percentages or length units.
Example: Sharp Stripes
Setting two colors to stop at the same point creates a hard line or a stripe.
/* Creates a hard, vertical stripe at 50% */
.stripe {
background-image: linear-gradient(to right, navy 50%, white 50%);
}
Using Transparency
Using RGBA or HSLA color formats allows you to fade a color to complete transparency, revealing the element's background-color or whatever is behind the element.
/* Fades from solid black to completely transparent */
.fade-out {
background-image: linear-gradient(to bottom, black, rgba(0, 0, 0, 0));
}
Interactive Gradient Demo
Experiment with different gradient types and settings in the live editor.