| title | The Background Gradient | ||||||
|---|---|---|---|---|---|---|---|
| description | Learn how to use CSS gradient functions (linear and radial) to create smooth, code-generated color transitions as an element's background without using image files. | ||||||
| keywords |
|
||||||
| tags |
|
||||||
| sidebar_label | 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.
Gradients are functions of the background-image property:
selector {
background-image: linear-gradient(...);
/* OR */
background-image: radial-gradient(...);
}A linear gradient transitions colors along a straight line. You must define a direction or angle, and at least two color stops.
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);
}A radial gradient transitions colors outward from a central point, radiating in a circular or elliptical 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);
}You can define color stops to control where the color transition begins and ends, using percentages or length units.
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 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));
}Experiment with different gradient types and settings in the live editor.