0%
Jan092017

# Motion Parallax: A Primer

## Resources

Motion Parallax is the name given to the phenomenon of objects closer to you seeming to move faster than objects farther away. If you've ever driven down a country road, you've probably noticed the scenery in the background seeming to move much slower than the power poles next to the road. "Parallax" by Nathaniel Domek How can we implement it? While it would be costly, and perhaps difficult, to implement a full 3D engine in CSS/JS (excluding the unreliable transform), we can fake it rather simply. An initial thought would be to manipulate the background-position property of an image, and that would work, but for reasons we'll soon find out, it's not ideal. One of the first things we need to do is decide the range of motion of the image desired, and the range of motion of the screen. If, for instance, we want our image to move 200 pixels over the height of the screen, each step of motion must be 200/$(window).height() pixels, starting from the moment the <div> is visible, or when$(window).scrollTop+$(window).height()==$(div).offset().top. See the results of this idea below. What's wrong with that? First and foremost, hard-coding anything will only lead to headaches down the road, and our above solution won't work for images much farther down a page. If you're on mobile, you may even see some of the <div> not covered by the image. On top of that, we have the problem of different sized background images. Ours fits roughly into a 600x400 space, because it has close to a 3:2 ratio. Other images might not be so lucky. We also run into the problem of using absolute pixel sizes at all — if we want to use percentages, or cover or contain for our background image, we're out of luck. The solution that we use has two separate <div>'s within the main <div>. This allows us to manipulate the "background" <div> in a straightforward way, while having content in a "content" <div>. See the full solution below.