CSS Gradients
35 minCSS Gradients allow you to display smooth transitions between two or more colors. They are treated as images by the browser, meaning you use them in the `background-image` property, not `background-color`.
There are three types: **Linear Gradients** (go down, up, left, right, or diagonally), **Radial Gradients** (radiate from a center), and **Conic Gradients** (rotated around a center point).
Gradients can be hard stops (stripes) or smooth blends. You can also use transparency to create overlays or fade-out effects.
Repeating gradients (`repeating-linear-gradient`) allow you to create patterns like stripes or plaid without needing external image files.
Key Concepts
- Gradients are generated images.
- Types: Linear, Radial, Conic.
- Defined by direction/angle and color stops.
- Can include transparency.
- Repeating gradients create patterns.
Learning Objectives
Master
- Creating linear and radial gradients
- Controlling direction and angles
- Using color stops and hints
- Creating patterns with repeating gradients
Develop
- Modern UI aesthetics
- Reducing HTTP requests (no image files needed)
- Creating complex backgrounds
Tips
- Always provide a solid `background-color` fallback for old browsers.
- Use tools like CSS Gradient Generator to visualize complex gradients.
- Overlay a semi-transparent gradient on an image to make text readable.
- Use `transparent` keyword for fade effects.
Common Pitfalls
- Using `background-color` instead of `background-image` (gradients won't show).
- Creating harsh, muddy transitions by mixing clashing colors without a middle step.
- Performance issues with very complex, layered gradients.
- Forgetting to specify direction (defaults to top-to-bottom).
Summary
- Gradients are code-generated images.
- They are versatile for backgrounds and UI.
- They reduce reliance on image assets.
- Linear, Radial, and Conic are the main types.
Exercise
Create a linear gradient background that transitions from blue to purple.
body {
background: linear-gradient(to right, #4facfe, #00f2fe);
min-height: 100vh;
}
Exercise Tips
- Try radial gradients: background: radial-gradient(circle, #4facfe, #00f2fe);
- Add multiple color stops: linear-gradient(to right, blue, purple, pink);
- Use angles: linear-gradient(45deg, blue, purple);
- Create repeating patterns: repeating-linear-gradient(45deg, blue, blue 10px, purple 10px, purple 20px);