O'Reilly

CSS Background Animations

By on  

Background animations are an awesome touch when used correctly.  In the past, I used MooTools to animate a background position.  Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks.  The following simple CSS snippet animates the background image (via background position) of a given element.

The CSS

We'll use CSS animations instead of transitions for this effect:

@keyframes animatedBackground {
	from { background-position: 0 0; }
	to { background-position: 100% 0; }
}

With the animation code in place, now it's time to apply it to an element with a background image:

#animate-area	{ 
	width: 560px; 
	height: 400px; 
	background-image: url(bg-clouds.png);
	background-position: 0px 0px;
	background-repeat: repeat-x;

	animation: animatedBackground 40s linear infinite;
}

The cloud background image within the sample element will elegantly scroll from left to right over a duration of 40 seconds, seamlessly repeating an infinite number of times.

How epic is it that we don't need to use JavaScript to manage these animations anymore?  Of course the mess of vendor prefixes to accomplish the animation sucks, but at least the animations are much more efficient and more easily configurable!

Track.js Error Reporting

Upcoming Events

Recent Features

  • fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • Create a Sheen Logo Effect with CSS

    I was inspired when I first saw Addy Osmani's original ShineTime blog post.  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

Incredible Demos

  • CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

  • CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

Discussion

  1. MaxArt

    May I suggest to use multiple background images to create a cool parallax effect in that cloud background?

  2. Easy and efficient! Thanks for this css trick!

  3. wow .. very awesome animation friend ,,,,,,,,, i love it .

  4. Wow, great post and very thorough. Out of interest, where did you get the cloud image from? I did a similar tutorial on my blog about using CSS sprites to create a basic button. I guess using the same idea you could even animate the background of the button.

  5. As MaxArt suggested, having multiple (small in file-size) backgrounds could create a cool effect. So I experimented! Check it out: http://www.creativewebgroup.co.uk/library/background.html

  6. As MaxArt suggested, having multiple (small in file-size) backgrounds could create a cool effect. So I experimented!

    Check it out: http://www.creativewebgroup.co.uk/library/background.html

    • My apologies for the multiple post! Browser wouldn’t load the comment!

  7. minhyung

    cool, But the many paint calls happen ~ during animation

  8. For this example and many others, the “from” keyframe is not needed. This works just as well:

    @keyframes animatedBackground {
        to { background-position-x:100%; }
    }
  9. Very nice tutorial. Your article, and MaxArt’s comment, encouraged me to create my own version, with parallax effect:

    Demo:
    http://demo.cmorales.es/background-animation/prefixed.html

    Tutorial (in Spanish):
    http://cmorales.es/tutorial/fondo-animado-con-css3/

  10. Hardeep Asrani

    great tutorial..going to try it for sure :)

  11. mick

    where do you put the first piece of code?

  12. Hey David,

    This is indeed an awesome post. I tried it and it felt really cool.

    However, when i expanded the width to say 1000 or 2000 to fit the screen width, the animation restarts from the 1st frame creating a start effect after some seconds and it doesn’t look like a seamless flow of animation. I hope you got me.

    Try increasing the width and reducing the animation time(seconds). :)

  13. Vincent

    I had the same problem with the stutter when the image reached the end and started over (as described by Priyank Rathod). The problem is either the width of the div or the image itself. You have to create the image in such a way that when it reaches the end within its div (or whatever – in my case it was a TD), it looks exactly as it would as if it were still at the beginning. You essentially have to define the width of the div and create the image to be the exact same width – minus the borders of the div – and the left side of the image has to connect to the right side seamlessly. (I also removed the width and height specs from the css but not sure if that made a difference.)

  14. Nice trick, looking awesome to me.

    What about the animation done in background all over the page. I means if Image goes smaller then the size of monitor then maybe some trouble will happen.

  15. apology, I came out excellent animation, unfortunately you can only see in firefox, and I can not see it or tablet or chrome, there is a kit for the other browsers, or in this case you could do, you and I hope your answer is urgent

  16. Amit

    why this is not working in chrome? can anybody explain? only working in the FF. Thanks in advance.

  17. Amit

    ops. fixed it :)

    @-webkit-keyframes animatedBackground{
    	from { background-position: 0 0; }
    	to { background-position: 100% 0; }
    }
    

    how fool i was. thanks for this David. much appreciated.

  18. Will

    Cool, but on old computers like mine it goes 90% CPU

  19. I have tried this out with an animation that extends the full width of the browser it works fine unless your on a big screen when you extend it outwards to full width it then goes from left to right! How do I stop that from happening?
    Thanks,

  20. Fabricio

    Hi, I used this code on my website’s footer and it works perfectly except it stops for a bit after a while as if it’s starting again. I’m not sure why, anyone can help me fix this bug? Check the dark bottom footer: http://www.alpinaweb.com.br/v1/

    I want it to look very smooth. Thanks a lot.

  21. hyperdunc

    Here’s one way to stop the animation skipping if you are using a larger div with a width of 100% document size:

    Set the div’s css background-size property to a multiple of the div’s width that is close to the image’s width.

    For example, with a div width of 1265px, I set:

    background-size: 2530px;

    2530px = 1265px x 2, which is slightly larger than my image width of 2247px.

    If you use a responsive layout, you’ll need to set background-size using javascript each time the document is re-sized.

  22. Ian

    Is it possible to use translate(x,y) on this?

  23. This is fantastic & very useful method however when using large background images with more than 60s animation time the animation becomes really really choppy… I’m trying to use translate(x,y) but have been able to apply it to only one image but it would be so great if it can be applied to all backgrounds to get a really smooth animation.

  24. Dude

    Hi,

    when using

    @keyframes animatedBackground {
    	to { background-position: 100% 0; }
    }

    you may get 2 problems. The animation skipping when it loops and the speed of the animation is depending on the size of the window/element.

    I recommend using:

    @keyframes animatedBackground {
    	to { background-position: 250 0; }
    }

    where 250px is the width of the picture.
    This way it will loop seamless and the animation won’t be faster on smaller screens.

  25. NOTE: If you want to use this on a 100% width element (such as the entire background of your site), you need to make a small modification.

    The width of your container should be 100% (ie. the body in this case).
    The ‘to’ position of the keyframe animation needs to be set to the negative value (if scrolling left, otherwise positive value) of the width of your image. This will prevent ‘glitching’ when the image reaches the end of it’s “wrap”, but the container still has space left over.

    For instance:

    @-webkit-keyframes animatedBackground {
        from { background-position: 0 0; }
        to { background-position: -2336px 0; }
    }
    .main-pane { 
        width: 100%; 
        height: 768px;
        background-image: url(../img/blurred_clouds2.png);
        background-position: 0px 0px;
        background-repeat: repeat-x;
    
        animation: animatedBackground 4s linear infinite;
        -ms-animation: animatedBackground 4s linear infinite;
        -moz-animation: animatedBackground 4s linear infinite;
        -webkit-animation: animatedBackground 4s linear infinite;
    }
    

    Hope that helps anyone trying to do this on width: 100% element.

  26. Suphicha

    quick question! does this CSS works on phone? Thanks!

  27. david

    Hi David
    Great resource you have here helping guys with codes et all.
    I tried to add the animated background to heade section of css style on my website, ( width is 960px height 300px) it didnt work and i tried the css multiple animated background it didnt help.
    I am using adobe dreamweaver 4.
    Please kindly do assist

    • David,

      Here is code that I was able to get working, which animates the entire background of the page.

      @-webkit-keyframes animatedBackground {
          from { background-position: 0 0; }
          to { background-position: -2336px 0; }
      }
      
      /* note that the background image I'm using is 2336px wide (as defined above also) */
      .container { 
          position: absolute;
          top: 0px;
          width: 100%; 
          height: 768px;
          z-index: 0;
          background-image: url(../img/blurred_clouds_des.png);
          background-position: 0px 0px;
          background-repeat: repeat-x;
          min-width: 500px;
      
          animation: animatedBackground 60s linear infinite;
          -ms-animation: animatedBackground 60s linear infinite;
          -moz-animation: animatedBackground 60s linear infinite;
          -webkit-animation: animatedBackground 60s linear infinite;
      }
      
  28. Nice,

    I’m experimenting with it… Using

    @keyframes animatedBackground {
    	from { background-position: -55% 90%; }
    	to { background-position: 155% 90%; }
    }
    

    I used negative and over 100 percentage to get the image out of screen-border. Will try the other methods later.

    And i used

    @media (min-width: 1100px) {
    
     }
    
    

    To only use it on big screens.

    Still experimenting… But fun..

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â New York

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...