Parallax Scrolling

adamlarosa

Adam La Rosa

Posted on July 12, 2020

Parallax Scrolling

Surfing around the web I've come across sites where when scrolling down the background seems to scroll at a different speed than the rest of the site. This is a technique called "Parallax Scrolling". Which can easily be done with only CSS. First what we can do is outline our HTML with a few layers.

<body>
    <div class="parallax">

        <div class="parallax__layer parallax__layer--back">
          <div class="title">This is the background</div>
        </div>
        <div class="parallax__layer parallax__layer--base">
          <div class="title">This is the foreground</div>
        </div>

    </div>
</body>

Here we set aside a couple of containers for our text, each with a class "title". Both of them are nested inside another class, "parallax__layer", then individualized by which layer they are in, in this case base & back. All of which is nested inside a container that is for all of our parallax scrolling content. Now for a bit of CSS!

.parallax {
    height: 100vh;
    overflow-x: hidden;
    overflow-y: auto;
    -webkit-perspective: 1px;
    perspective: 1px;
}

.parallax__layer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

This sets our container & the base for the layers underneath by setting their positions to "absolute".

.parallax__layer--base {

    -webkit-transform: translateZ(0);
    transform: translateZ(0);
}

.parallax__layer--back {
    -webkit-transform: translateZ(-1px);
    transform: translateZ(-1px);
}

Here is where we have the distinction between our layers. By setting our transform property to different values on the Z axis we can differentiate between the two layers.

* {
    margin:0;
    padding:0;
}

body {
    font: 100% / 1.5 Arial;
}
.parallax {
    font-size: 200%;
}
.parallax__layer {
    padding: 100vh 0;
}

.title {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

With this last bit of formatting we can set the format of our layers and voila! Smooth scrolling at different speeds for our site!

💖 💪 🙅 🚩
adamlarosa
Adam La Rosa

Posted on July 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related