search ]

Animating Gradients: A Guide to Smooth Transitions in CSS

In CSS, it is not possible to perform animation or partial gradient changes using the transition property. In other words, the following transition won’t work:

.gradient {
  min-height: 200px;
  background-image: linear-gradient(
    to right,
    hsl(49.68, 97.89%, 62.75%),
    hsl(200, 51.54%, 44.51%)
  );
  transition: background-image 0.5s linear;
}

.gradient:hover {
  background-image: linear-gradient(
    to right,
    hsl(200, 51.54%, 44.51%),
    hsl(49.68, 97.89%, 62.75%)
  );
}

In the above code, the transition between states won’t be smooth but will immediately jump between the two states. It looks like this:

Without effect

This can be solved to achieve the desired effect using pseudo-elements along with setting the transform property on opacity. The first thing to do is to set the gradient to the element.

Then place the pseudo-element so that it covers the entire element and set the second gradient to this element.

In order to achieve the same transition, the desired effect can now be applied using the opacity transition on the same pseudo-element. This is done as follows:

.gradient {
  position: relative;
  min-height: 200px;
  background-image: linear-gradient(
    to right,
    hsl(49.68, 97.89%, 62.75%),
    hsl(200, 51.54%, 44.51%)
  );
  z-index: 1;
}

.gradient::before {
  position: absolute;
  content: "";
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(
    to right,
    hsl(200, 51.54%, 44.51%),
    hsl(49.68, 97.89%, 62.75%)
  );
  z-index: -1;
  transition: opacity 0.5s linear;
  opacity: 0;
}
.gradient:hover::before {
  opacity: 1;
}

The same pseudo-element is initially hidden due to the opacity: 0 property. On hover, we change the opacity to 1, creating a smooth transition where the main gradient smoothly transitions to the pseudo-element’s gradient.

We also need to appropriately set the z-index so that the pseudo-element is always in the bottom layer, i.e., below the element itself.

This requires a bit of code, but unfortunately, this is the ideal way to achieve this effect. In any case, the result looks like this:

With effect

The text shadow effect was added using the cool text-shadow property. Here are some examples of adding shadows with text-shadow.

That’s it.

Roee Yossef
Roee Yossef

I develop pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!