How to set a Gradient Background Color with CSS

To set a gradient background color with CSS, you need to add the linear-gradient() function to your background property.

Let’s create a simple box class and try it out:

<div class="box"></div>
.box {
  width: 200px;
  height: 200px;
  background: linear-gradient(yellow, red);


You can change which colors start and finish by reordering them inside the linear gradient function:

/* Starting red, finishing yellow */
 background: linear-gradient(red, yellow);

Change the linear-gradient angle/tilt

As you can see in the examples above, the linear-gradient() function creates a top to bottom gradient by default. You can easily change the gradient angle to anything you want.

For example, here’s a linear gradient that is tilted 45 degrees:

/* Starting yellow, finishing red */
linear-gradient(45deg, yellow, red);


You can use any degree from 0 to 360.

Use HEX, RGB, or RGBa for your gradients

You can use the HEX, RGB, and RGBa color models for your linear-gradients. The RGBa is the most flexible one in that it allows you to use an Alpha channel (for transparency) on your linear gradients.

As you can see below, you can get as creative as you want with your gradients when using RGBa:

Here’s the CSS for the linear-gradient example above:

    background: linear-gradient(217deg, 
    rgba(255,0,0,0) 70.71%),
    rgba(0,255,0,0) 70.71%),
    rgba(0,0,255,0) 70.71%);

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on