2 Feb 2023

Creating a Parallax Scrolling Effect with HTML, CSS, and JavaScript

Parallax scrolling is a web design technique in which the background of a web page moves at a different speed than the foreground, creating a 3D illusion. This effect can add depth and visual interest to a web page, and can be implemented in HTML, CSS, and JavaScript. In this blog, we will go through the process of creating a basic parallax scrolling effect on a web page.

HTML

To start, we will create a basic HTML structure for our web page. We will have a header, a main content section, and a footer. In the main content section, we will have several sections that will serve as our parallax layers.

<header>
  <h1>Header</h1>
</header>

<main>
  <section class="layer layer-1">
    <h2>Layer 1</h2>
  </section>
  <section class="layer layer-2">
    <h2>Layer 2</h2>
  </section>
  <section class="layer layer-3">
    <h2>Layer 3</h2>
  </section>
</main>

<footer>
  <h3>Footer</h3>
</footer>

CSS

Next, we will add some basic styling to our HTML structure using CSS. We will give each layer a different background color and position them one on top of the other using absolute positioning.

body {
  height: 100%;
  margin: 0;
  overflow: hidden;
  position: relative;
}

header,
footer {
  height: 10%;
  width: 100%;
  background-color: lightgray;
  text-align: center;
}

.layer {
  height: 80%;
  width: 100%;
  position: absolute;
  top: 10%;
}

.layer-1 {
  background-color: lightblue;
}

.layer-2 {
  background-color: lightcoral;
}

.layer-3 {
  background-color: lightgreen;
}

JavaScript

Now that we have our HTML structure and CSS styling in place, we can add the JavaScript code to create the parallax scrolling effect. To do this, we will listen for the scroll event on the window and use the scrollTop property to calculate the distance that has been scrolled. We will then use this value to update the transform property of each layer, which will cause them to move at different speeds, creating the parallax effect.

const layers = document.querySelectorAll('.layer');

window.addEventListener('scroll', () => {
  const scrollTop = window.pageYOffset;
  
  layers.forEach((layer, index) => {
    const speed = index / 4 + 1;
    layer.style.transform = `translateY(${scrollTop * speed}px)`;
  });
});

And that's it! With these simple HTML, CSS, and JavaScript code snippets, we have created a basic parallax scrolling effect. Of course, there are many ways to customize and enhance this effect, such as using different easing functions, adding images or videos as backgrounds, and more. This blog provides a good starting point for creating a parallax scrolling effect on a web page, and can serve as a foundation for further experimentation and customization.