Search code examples
parallaxcss-transforms

translateZ Parallax Scrolling Doesn't Work


I'm trying to do a page with simple, pure-CSS parallax sections. I applied perspective to the body element and preserve-3d to the section containers, but the background images aren't scrolling at a slower rate, they're just scrolling normally.

HTML:

<div class="p-section">
    <div class="content"></div>
    <div class="bg"></div>
</div>
<div class="p-section">
    <div class="content"></div>
    <div class="bg"></div>
</div>
<div class="p-section">
    <div class="content"></div>
    <div class="bg"></div>
</div>

CSS:

body {
    width: 100vw;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: scroll;
    perspective: 10px;
}
.p-section {
    transform-style: preserve-3d;
    height: 100vh;
    position: relative;
}
.content,
.bg {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
.bg {
    transform: translateZ(-10px) scale(2);
}

Here's a CodePen.


Solution

  • perspective doesn't work when applied to the body element. You need to wrap your sections in a containing element and apply perspective to that.

    HTML

    <div class="p-container">   
        <div class="p-section">
            <div class="content"></div>
            <div class="bg"></div>
        </div>
        <div class="p-section">
            <div class="content"></div>
            <div class="bg"></div>
        </div>
        <div class="p-section">
            <div class="content"></div>
            <div class="bg"></div>
        </div>
    </div>
    

    CSS

    .p-container {
        width: 100vw;
        height: 100vh;
        overflow-x: hidden;
        overflow-y: scroll;
        perspective: 10px;
    }
    

    Example CodePen