Smoothing the parallax scrolling of a background image

Chuck Le Butt picture Chuck Le Butt · Apr 3, 2013 · Viewed 60.5k times · Source

I've done a bit of research and written a simple bit of jQuery that scrolls the background at a slightly different pace to the foreground, creating a parallaxing effect as you scroll down a website.

Unfortunately it's a bit jerky.

Here's the basic layout of the HMTL:

<body>
    <section>
        Site content goes here.
    </section>
</body>

Here's the CSS:

body {
    background-image: url('../images/bg.png');
    background-repeat: repeat-y;
    background-position: 50% 0;    
}

Here's the JS:

$(window).scroll(function () {
    $("body").css("background-position","50% " + ($(this).scrollTop() / 2) + "px");
});

https://jsfiddle.net/JohnnyWalkerDesign/ksw5a0Lp/

Pretty simple, but my problem is that it's a bit jerky when you scroll, even on a powerful computer.

Is there a way to make the background parallax animate smoothly?

Answer

mcmonkeys1 picture mcmonkeys1 · Jun 4, 2014

Add transition property to your CSS so it can be accelerated by the GPU like this:

body {
    background-image: url('../images/bg.png');
    background-repeat: repeat-y;
    background-position: 50% 0;    
    transition: 0s linear;
    transition-property: background-position;
}