CSS Gradients: Painting with Code
Gradients eliminate the need for large background image files. By using mathematical color interpolations, we can create scalable, resolution-independent designs that load instantly.
Linear Gradients
The linear-gradient() function creates an image consisting of a progressive transition between two or more colors along a straight line.
You can declare the direction using keywords (to right, to bottom left) or specific angles (45deg). If no direction is specified, it defaults to top-to-bottom.
Radial Gradients
A radial-gradient() emerges from a single point and smoothly spreads outward. The default shape is an ellipse matching the element's proportions, but it can be forced to a circle.
You can also dictate the gradient's origin by appending at [position], such as circle at top left, providing immense flexibility for mimicking lighting sources.
Color Stops & Hard Lines
By default, colors distribute themselves evenly. However, you can dictate exactly where a color should reach its pure value using percentages or lengths (e.g., red 20%).
- Smooth blends:
red 10%, blue 90%leaves a long transition space in between. - Hard lines: Place two colors at the same exact position:
red 50%, blue 50%creates a crisp, immediate change with no blending.
View Performance Tips+
Gradient stacking: You can apply multiple gradients to the same element by separating them with commas. The first declared gradient is layered on top. Use rgba() with transparency to blend them visually!
❓ Frequently Asked Questions
Why use background-image instead of background-color?
In CSS, a gradient is technically considered a dynamically generated image, not a flat color. Therefore, it must be assigned to the `background-image` property. Using `background` (the shorthand) also works and is very common.
How do I make a striped background?
Use `repeating-linear-gradient()`. By using exact pixel values for your color stops, you can create hard stripes that repeat infinitely across the container.
background: repeating-linear-gradient(
45deg,
yellow,
yellow 10px,
black 10px,
black 20px
);What is a conic gradient?
A conic gradient places color transitions rotated around a center point (like a color wheel or a pie chart), rather than radiating outwards from the center. The syntax relies heavily on degrees (`deg`) instead of pixels or percentages.
