HTML5 and CSS3 Advent 2011

Parallaxing CSS3 backgrounds

In 2011 scrolling was the new black. We've seen all kinds of site that use some kind of cool way to scroll. The effect is called parallax scrolling and has been around since the days of Super Mario Bros (probably longer). The idea is pretty simple; you have multiple layers which you move at different speeds to give the illusion of depth.

How does it work?

The effect is achieved by moving layers with sprites at different speeds.In a platform game you'd move the backmost layer at a much slower speed than the front-most layer. Our example above we chose to have a fixed scenery where the viewer moves but always looks at the same point in the distance.

The principle is best illustrated but the diagrams below. Both diagrams depict the scene from above (at least how it should be virtually). In the base position, all layers are centered in the box and are anchored to the viewer's line of sight. Once the viewer (in the example your mouse cursor) moves, the layers move too. Because the viewer moves but is still looking at the same center, each of the layers move a different amount.

Base position
Base position
Moved position
Moved position

Of course we've added the layer with multiple backrounds in css3. On mouse-move we just calculate the new background-position of each layer and set it accordingly.

Show us the source!

Feel free to look around the different source files we used for this example.

Check out our all new HTML & CSS Advent 2012