Animate CSS Gradient Background

August 25, 2020 by Andreas Wik

animate css gradient background

Let’s look at how we can animate a CSS gradient background.

The trick is to make the background-size larger than the element it applies to, then change the background-position. Add either a transition or use @keyframes to animate the position change.

 

Animate gradient background on hover

Let’s create a button:

<button>awik.io</button>

 

I want this button to have a pink-ish to orange-ish gradient in its default state, and then transition to a blue to blue gradient on hover. I create this gradient and set the background-size to 300% wide, so the blue gradient is outside of the visible view. Play around with these values until you get it the way you want.

Also add a transition for the background-position.

button {
  background: linear-gradient(45deg, #d05c9c, #e1664c, #66c3dd, #536eec);
  background-size: 300% 100%;
  background-position: 0 0;
  transition: background-position 1.5s;
}

 

On hover, change the background-position:

button:hover {
  background-position: 100% 0;
}

 

That should do it – CodePen demo:

See the Pen Button gradient animation by Andreas Wik (@andreaswik) on CodePen.

 

 

Infinite looping gradient background animation

If we want to animate a gradient background indefinitely we can use @keyframes instead.

Just as in the previous example, set the gradient background and the background-position.

body {
	background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
	background-size: 400% 400%;
}

 

Create the animation using @keyframes:

@keyframes gradient {
	0% {
		background-position: 0% 50%;
	}
	50% {
		background-position: 100% 50%;
	}
	100% {
		background-position: 0% 50%;
	}
}

 

Add the gradient animation to the element:

body {
	animation: gradient 15s ease infinite;
}

 

Manuel Pinto has created a brilliant example of this:

See the Pen Pure CSS Gradient Background Animation by Manuel Pinto (@P1N2O) on CodePen.

 

Enjoy!

 

Share this article

Recommended articles

@awikio