CSS Animated Gradient Background

CSS Animated Gradient Background

Do you ever look at a solid-color background on a website and think to yourself what a bore? Most websites are guilty of being too boring. That’s great if you want the focus to be on your message, but you can show so much more creativity by adding a little color and animation.

If you don’t want to use JavaScript or Jquery to create an interactive background, adding a CSS animated gradient background is one way to do it.

CSS is short for cascading style sheets and is used for describing the presentation layer of a document. In short, it is how you style your website. You can’t do too much if you only use HTML to build your website. Adding a little CSS can help you bring things to life.

Have a look at the incredible pink-to-blue transition in this animation! How cool would that be as a background on your web page?

Making a CSS Animated Gradient Background in 5 minutes

The code for creating this is surprisingly simple. Want to add an animated gradient background to your website? Let’s make one together!

Step one is creating our HTML file and making sure we have a class to target with our CSS. For this example, let’s just create a <body> element and give it a class name of “gradient background” like so:

<body class="gradient-background">
</body>

Simple enough right? You can add this class to any element which you want to have an animated background. Let’s get down to the important part; adding the CSS.
We’ll start off by defining two classes with the following properties:

body {
  box-sizing: border-box;
  background-color: #fff;
}
.gradient-background {
  background: linear-gradient(300deg, #007bff, #000, #ff00ea);
  background-size: 180% 180%;
  animation: gradient-animation 20s ease infinite;
}

In order for everything to fit properly on the page, we’ll need to set the “box-sizing” property to “border-box” on the body element. The background size of the “gradient-background” class must also be set to be larger than it’s parent container in order to show the effect properly.

Once we have these two classes defined, it is time to bring it all to life with animations.

For this, we are going to use Keyframes. Simply add the following code to your CSS file and watch the magic happen:

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

As we can see here, our gradient is moving back and forth, creating the illusion that it is flowing. Pretty cool stuff huh? Tweak the colors and the animation speed on your project to get a unique and creative background.

Check out the video tutorial

Leave a Reply