Code snippet: The easiest way for a parallax background with CSS and JavaScript

Here is the JavaScript part:

window.addEventListener("scroll", event => {
    document.body.style.backgroundPosition = "0px -" + (window.pageYOffset / 2) + "px";
});

Here is how the CSS part may look like:

body {
    background-image: url(./images/bg1.jpg);
    background-size: 100%;
    background-repeat: no-repeat;
    background-attachment: fixed; // this is important
}

 

Here is an example of the result:

Schreibe einen Kommentar