How to add a gradient background
Short answer
A gradient is an image, so it goes in background:
<div style="height: 100px; background: linear-gradient(to right, deepskyblue, mediumpurple);"></div>The first value is the direction: to right, to bottom (the default) or an angle like 135deg. Then come the colors.
Several colors and stops
There can be any number of colors, each with its own position. If two positions match, you get a hard edge instead of a smooth blend:
<div style="height: 50px; margin-bottom: 6px; background: linear-gradient(135deg, gold, tomato 50%, crimson);"></div>
<div style="height: 50px; background: linear-gradient(to right, teal 50%, orange 50%);"></div>A radial gradient
radial-gradient() spreads out from the center as a circle or an ellipse:
<div style="height: 120px; background: radial-gradient(circle at 30% 40%, white, lightskyblue 40%, navy);"></div>A gradient over an image
With a comma you can lay a semi-transparent gradient over a photo so text on it stays readable:
.hero { background: linear-gradient(rgb(0 0 0 / 0%), rgb(0 0 0 / 70%)), url(/media/photo-800x500.jpg) center / cover; }Common mistake
People write background-color: linear-gradient(...) — and nothing happens. A gradient is an image, not a color, so it only works in background or background-image.
Functions used in this recipe
- linear-gradient() — A smooth transition between colors along a straight line — used as a background image.
- radial-gradient() — A transition between colors from a center outwards.
- background-image — One or more background images: files or gradients.