How to Create Linear Gradient in CSS: Simple Guide
Use the
linear-gradient() function in CSS to create a smooth transition between colors along a straight line. Apply it as a value to properties like background or background-image with a direction and color stops.Syntax
The linear-gradient() function creates a gradient along a straight line. It takes a direction (angle or keywords) and two or more colors as stops.
- Direction: Can be an angle like
45degor keywords liketo right. - Color stops: Colors where the gradient changes, e.g.,
red,blue.
css
background: linear-gradient(direction, color-stop1, color-stop2, ...);
Example
This example shows a linear gradient from blue on the left to green on the right applied to the whole page background.
css
body {
height: 100vh;
margin: 0;
background: linear-gradient(to right, blue, green);
}Output
The browser background smoothly changes from blue on the left side to green on the right side across the entire page.
Common Pitfalls
Common mistakes include:
- Forgetting to specify direction, which defaults to top to bottom.
- Using invalid color names or missing commas between colors.
- Applying the gradient to elements without size, so it may not be visible.
css
/* Wrong: missing commas and invalid color */ background: linear-gradient(to right red, blue); /* Correct: commas between colors */ background: linear-gradient(to right, red, blue);
Quick Reference
| Property | Description | Example |
|---|---|---|
| direction | Angle or keyword for gradient direction | to right, 45deg |
| color stops | Colors and optional stop positions | red, yellow 50%, green |
| usage | Apply to background or background-image | background: linear-gradient(to bottom, red, blue); |
Key Takeaways
Use
linear-gradient() with direction and colors to create smooth color transitions.Specify direction clearly using angles or keywords like
to right.Separate colors with commas and ensure the element has visible size.
Apply gradients to
background or background-image properties.Test gradients in the browser to see the smooth color blend effect.