Parallax & CSS3


Mouse over the landscape to see the effect

I’m spending the bulk of this weekend at the HTML5 Tools Jam organized by my friends Darren & Darius of Boston Game Jams. I am working towards adding parallaxing background support to the ALES level editor for the Akihabara HTML5 game engine. I have the benefit of direct access to the creators of ALES, the aforementioned Darren Torpey & Darius Kazemi, but my first goal didn’t even involve Akihabara: I just wanted to see if there was a way to use CSS3’s support for multiple backgrounds to create a parallax effect within a div. As you can see above (if you’re using Chrome, Safari or Opera), it does!

The above div contains two .png background images with a repeat-x property specified. Just as you define multiple backgrounds through comma-separated url() statements, so can you change the position of all background images within a div by using JavaScript to pass comma-separated background positions. In this case I’m using setInterval to quickly create a continuous animation—something along these lines:

setInterval(function() {
    pos1+=4;
    pos2+=1;
    $('#css3parallaxdemo').animate({
        'background-position':
            pos1 + '% bottom,' +
            pos2 + '% bottom'
    }, 20, 'linear');
}, 20);

The easy part done, I am looking forward to diving into ALES. It’s doubtful I will be able to get full two-dimensional parallax motion ready by the end of the weekend due to other commitments, but many other people here are also working on ALES and I’m looking forward to seeing where the platform goes. (I recommend taking a look at Ryan Kahn’s Akihabara plugins system as an example of awesome recent developments.)

One thought on “Parallax & CSS3

  1. K.Adam White says:

    Update November 2013: I\’ve moved the parallax scrolling demo into its own HTML page, and improved the code to use CSS3 transitions instead of expensive jQuery animations. View the source of the above iframe for more!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.