translateZ 视差滚动不起作用

translateZ Parallax Scrolling Doesn't Work

我正在尝试制作一个包含简单、纯 CSS 视差部分的页面。我将 perspective 应用到 body 元素,将 preserve-3d 应用到部分容器,但背景图像的滚动速度并没有变慢,它们只是正常滚动。

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);
}

这是 CodePen

perspective 应用于 body 元素时不起作用。您需要将您的部分包装在一个包含元素中并对其应用 perspective

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