CSS
π― What is linear-gradient()?
linear-gradient() creates a gradual color transition in a specific direction.
The colors smoothly blend into each other across the background.
π§© Simple Definition
linear-gradient() = creates a smooth linear color transition
π‘ Basic Syntax
background: linear-gradient(direction, color1, color2, ...);
π§ Parameters
1. Direction
Defines the direction of the gradient.
Common Direction Values
| Value | Direction |
|---|---|
| to right | Left β Right |
| to left | Right β Left |
| to bottom | Top β Bottom |
| to top | Bottom β Top |
You can also use angles:
45deg
90deg
180deg
2. Colors
Defines the colors used in the gradient.
At least two colors are required.
You can use:
- named colors
- HEX colors
- RGB/RGBA
- HSL/HSLA
π§© Basic Examples
1. Left to Right Gradient
background: linear-gradient(to right, red, blue);
π The color starts as red on the left and smoothly transitions to blue on the right.
2. Top to Bottom Gradient
background: linear-gradient(to bottom, yellow, green);
π Yellow starts at the top and transitions into green at the bottom.
3. Diagonal Gradient
background: linear-gradient(45deg, pink, purple);
π The gradient appears diagonally at a 45-degree angle.
4. Multiple Colors
background: linear-gradient(
to right,
red,
orange,
yellow,
green,
blue
);
π Creates a rainbow-style gradient π
π¨ Using Transparent Colors
You can combine gradients with transparency using rgba().
Example
background: linear-gradient(
to right,
rgba(255,0,0,0.7),
rgba(0,0,255,0.7)
);
π Creates a semi-transparent gradient effect.
π§© Practical Example
Hero Section Background
.hero {
height: 400px;
background: linear-gradient(
to right,
#4facfe,
#00f2fe
);
}
π This creates a modern blue gradient background often used in landing pages.
π¨ Combining Gradients with Images
Gradients can also be layered over images.
Example
.hero {
background-image:
linear-gradient(
rgba(0,0,0,0.5),
rgba(0,0,0,0.5)
),
url("hero.jpg");
}
π The dark gradient overlays the image, making text easier to read.
β οΈ Important Notes
- Gradients are treated as background images in CSS.
- They do not require uploading an actual image file.
- Gradients are responsive and scale automatically.
This makes them lightweight and performance-friendly.
π§ Common Use Cases
linear-gradient() is commonly used for:
- hero sections
- buttons
- banners
- overlays
- cards
- modern UI backgrounds
βοΈ Difference Between Solid Colors and Gradients
| Solid Color | Gradient |
|---|---|
| Single color | Multiple blended colors |
| Simple appearance | More dynamic appearance |
| Flat design | Depth and visual interest |
