Linear Gradients

Go back to HTML and CSS Index

Gradients are (often) smooth transitions between a number of different colors.

background-image: linear-gradient()

To create a linear gradient with CSS, you use the background-image property with the value set to linear-gradient():

section {
background-image: linear-gradient(direction, color-stop1, color-stop2)
}
1.10 | Syntax

If you don't type in a direction, it goes from top (color-stop1) to bottom (color-stop2).

Example 1 (no direction set)

div {
background-image: linear-gradient(red, yellow);
height: 60px;
}
1.21 | Linear gradient without the direction set

Example 2 (direction set to right)

div {
background-image: linear-gradient(to right, red, yellow);
height: 60px;
}
1.22 | Linear gradient with the direction set to right

Other posible directions include: to right bottom or to bottom right, to bottom, to bottom left or to left bottom, to left, to left top or to top left, to top, to top right or to right top.

Example 3 (direction set to 140deg)

div {
background-image: linear-gradient(140deg, red, yellow);
height: 60px;
}
1.23 | Linear gradient with the direction set to 140deg

The deg value represents an angle in degress. One full circle is 360deg.

Example 4 (customization of the gradient)

div {
background-image: linear-gradient(to right, red 60%, yellow);
height: 60px;
}
1.24 | Linear gradient with customization

We may customize the gradient by adding percentages to the colors that define how much space they may take up themselves before the gradient kicks in.

Example 5 (customization of the gradient)

div {
background-image: linear-gradient(to right, red 20%, yellow 20%);
height: 60px;
}
1.25 | Linear gradient with customization

We may create the illusion of a sharp line between two colors by giving both the same percentage value - note that it doesn't have to sum up to 100%

Example 6 (adding more colors)

div {
background-image: linear-gradient(to right, red 50%, yellow, red);
height: 60px;
}
1.26 | Linear gradient with 3 colors and customization

To add more colors to the mix, simply type in more colors.

Example 7 (creating stripes)

div {
background-image: linear-gradient(to right, red 20%, yellow 20% 40%, red 40%);
height: 60px;
}
1.27 | Linear gradient with 3 colors and customization

This example uses multi-position color stops, with adjacent colors having the same color stop value, creating a striped effect. The first color red takes up the space from 0-20, yellow then starts at 20 and stops at 40, and red then takes up whatever is left.