Moving Background using CSS

asherscott

Asher Scott

Posted on May 23, 2022

Moving Background using CSS

A moving background is a really simple way to spice up your website. It is also surprisingly simple to do.

HTML:

    <div id="background">
      <div id="effect"></div>
    </div>
Enter fullscreen mode Exit fullscreen mode

Here are our two divs that will contain our static background image, and our moving overlay for that image. Note that you can have any number of these divs, moving or not.

CSS:

#background {
  background-image: url("../public/transport1_touchup.png");
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  width: 100%;
  height: 100vh;
  z-index: -200;
}

#effect {
  position: absolute;
  background-image: url("../public/transport1_effects.png");
  width: 200vw;
  height: 100vh;
  animation: slide 20s ease-in-out infinite;
}

@keyframes slide {
  0%,
  100% {
    transform: translate(0px);
  }
  50% {
    transform: translate(-25vw);
  }
}
Enter fullscreen mode Exit fullscreen mode

This is our css for our two divs, as well as the keyframes for our slide animation. For this particular effect, I needed to make sure the overlay effect was much wider than the background image, yours may be different depending on your needs.

In some circumstances, it might make more sense to turn your effect into a repeating video or gif, and both have their pros and cons.

I hope this post was helpful, go get creating!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
asherscott
Asher Scott

Posted on May 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About