CSS Gradients


CSS gradients make it possible to smoothly transition between two or more selected colors.

CSS describes three kinds of gradients:

  • Linear Gradients (goes down/up/left/right/diagonally)
  • Radial Gradients (defined by their center)
  • Conic Gradients (rotated around a center point)

CSS Linear Gradients

To create a smooth transition of colors, you must select at least two different colors. Think of these colors as dots on a line, and the computer will seamlessly merge them. You can also decide where this color change should start and the direction it should follow..

Syntax

background-image: linear-gradient(direction, color-stop1, color-stop2, ...);

Direction - Top to Bottom (this is the usual way)

In this instance, we see a gradual change in color from red to yellow, beginning at the upper part.

top to bottom (default)

Direction - Left to Right

Here's an example that displays a color gradient. The gradient begins on the left side and goes from red to yellow.

left to right

Direction - Diagonal

To make a diagonal gradient, you need to specify where it should begin both horizontally and vertically on the webpage.

In this example, there's a color blend starting at the top left and going diagonally to the bottom right. It starts with red and smoothly turns into yellow.

top left to bottom right

Using Angles

If you want to control the appearance of a gradient, you can choose an angle instead of the typical directions like up, down, left, or right. When you set the angle to 0 degrees, it means the gradient goes from the top of the element to the bottom. If you set it to 90 degrees, it means the gradient goes from the left side to the right side. And if you select 180 degrees, it means the gradient goes from the bottom of the element to the top.

Syntax

background-image: linear-gradient(angle, color-stop1, color-stop2);

The next example demonstrates the usage of angles in linear gradients:

180deg


Using Transparency

CSS gradients can create a fading effect by allowing you to use transparent colors.

To make an object transparent, we use the rgba() function to select its colors. Inside the rgba() function, the last number can range from 0 to 1. This number indicates the level of transparency in the color: 0 means it's entirely transparent, and 1 means it's entirely opaque (no transparency at all).

In this illustration, we use a linear gradient that begins on the left side. Initially, it's invisible, and then it slowly turns into a bright red shade.


Repeating a linear-gradient

The repeating-linear-gradient() function is used to create a repeating pattern using linear gradients.