Gradients

Learn how to use gradient utilities for the background.

Background as a gradient

Tailwind also lets us set the background as a gradient, which requires us to specify multiple classes on the same element. This is the first time we have seen a case where we need multiple Tailwind classes to get something to work right. We’ll see this pattern more frequently as we look at page layout options in the next chapter.

In pure CSS, we specify a gradient by assigning the background-image property a value from a linear-gradient function. We specify a direction, a from color (starting point of the gradient), and a to color (the ending point). Optionally, we can specify a via color, which is a middle point.

Gradient utility

Tailwind provides utilities with the pattern, .bg-gradient-to-{direction}, and the four sides as directions: top (t), bottom (b), right (r), and left (l). So .bg-gradient-to-t means the gradient from color starts at the bottom and shades to the to color, which is at the top, while .bg-gradient-to-r means that the from color is at the left, and the to color is at the right.

We also get four corner directions— top left (tl), top right (tr), bottom left (bl), and bottom right (br). These are combined to provide a diagonal gradient. Therefore, .bg-gradient-to-tr is a gradient going diagonally from bottom left to top right.

Note: bg-none clears the gradient.

With the direction set, we can add in the colors. We use the same color names we have already seen, but with the prefixes .from-, .to-, and .via-. To go from red to blue and right to left, we would need three classes:

bg-gradient-to-l from-red-500 to-blue-500

If we want to stop at yellow in the middle, we would add a via keyword:

bg-gradient-to-l from-red-500 to-blue-500 via-yellow-500

If we specify from or both from and via without specifying a to color, the gradient will shade toward transparent.

In the following playground, we’ll look at the example of grayscale:

Get hands-on with 1200+ tech skills courses.