search
HomeWeb Front-endCSS TutorialCSS practical tips: Use parallax to achieve cool interactive effects

CSS practical tips: Use parallax to achieve cool interactive effects

This article will introduce a little trick to use CSS to achieve scrolling parallax effect, and use this trick to create some interesting interactive special effects. [Learning video sharing: css video tutorial, web front-end]

Regarding using CSS to achieve the scrolling parallax effect, there is a previous article that describes the specific solution in detail - CSS to achieve parallax effect, interested students can read this article first.

Here, a pure CSS parallax technique will be used:

Use transform: translate3d to achieve scrolling parallax

CSS is used here 3D, achieving scrolling parallax effect.

The principle is:

  • We set transform-style: preserve-3d and perspective: xpx to the container, Then the child elements in this container will be located in the 3D space.

  • Then set different transform: translateZ() for the child elements. At this time, different elements The distance from the screen (our eyes) in the 3D Z-axis direction is also different

  • Scroll the scroll bar because the child elements are set to differenttransform: translateZ(), then the up and down distance they scroll translateY relative to the screen (our eyes) is also different, which achieves the effect of scrolling parallax.

About transform-style: preserve-3d and perspective This article will not go into too much length, and readers will understand by default. Understand it. It’s not very clear yet. You can learn about CSS 3D first.

The core code representation is:

<div>
    <div>translateZ(-1)</div>
    <div>translateZ(-2)</div>
    <div>translateZ(-3)</div>
</div>
html {
    height: 100%;
    overflow: hidden;
}

body {
    perspective: 1px;
    transform-style: preserve-3d;
    height: 100%;
    overflow-y: scroll;
    overflow-x: hidden;
}

.g-container {
    height: 150%;

    .section-one {
        transform: translateZ(-1px);
    }
    .section-two {
        transform: translateZ(-2px);
    }
    .section-three {
        transform: translateZ(-3px);
    }
}

The summary is the parent element settings transform-style: preserve-3d and perspective: 1px, Set different transform: translateZ on the child elements and scroll the scroll bar. The effect is as follows:

CSS practical tips: Use parallax to achieve cool interactive effects

CodePen Demo -- CSS 3D parallax

Obviously, when the scroll bar is scrolled, the displacement degree of different sub-elements is visually different, which achieves the so-called scrolling parallax effect.

Use CSS parallax to achieve cool interactive effects

OK, with the above foundation, let’s take a look at these two interesting interactive effects. Courtesy provided by wheatup, the 日Server No. 1 cutter in the group.

Let’s look at the first effect first:

The effect is that text is displayed alternately in layers of different heights, and during the scrolling process, it will There is an obvious 3D parallax effect.

This effect is not difficult. The core lies in:

  • Using

    transform-style: preserve-3d and perspective Construct different levels of effects and create parallax effects

  • Use the

    ::before, ::after of elements to create a 3D effect

Let’s look at a minimized DEMO:

<div>
    <div></div>
    <div></div>
    <div></div>
</div>
.g-container {
    height: 150vh;
    perspective: 600px;
}

.g-box {
    width: 200px;
    height: 200px;
    background: #999;
    transform-style: preserve-3d;

    &::before,
    &::after {
        content: "";
        position: absolute;
        right: 0;
        left: 0;
        transform-style: preserve-3d;
        height: 200px;
        background-color: #ccc;
    }
    &::before {
        transform-origin: top center;
        top: 0;
        transform: rotateX(-90deg);
    }
    &::after {
        transform-origin: bottom center;
        bottom: 0;
        transform: rotateX(90deg);
    }
}
Scroll the

g-container container to get a 3D effect:

Since we also need the parallax effect, we need to assign different

translateZ() to different layers. We slightly modify the code and give each g-box In the middle, add another layer of normal div, and add a translateZ() to each g-box.

<div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
.g-container {
    width: 400px;
    height: 150vh;
    perspective: 800px;
}

.g-normal {
    width: 200px;
    height: 200px;
    background: #666;
    transform-style: preserve-3d;
}

.g-box {
    width: 200px;
    height: 200px;
    background: #999;
    transform-style: preserve-3d;
    transform: translate3d(0, 0, 200px);

    &::before,
    &::after {
        // ... 保持不变
    }
}
  • Since the translateZ values ​​of

    g-box and g-normal are different, a parallax effect will occur during scrolling

  • Since the

    translateZ value of g-box is translateZ(200px), the rotateX# of the two pseudo-elements ## is positive and negative 90deg, and the height is 200px, so g-box and g-normal can just pass The two pseudo-elements of g-box are connected

  • Finally, the effect is as shown above:

DEMO's Complete code:

CodePen Demo - 3D Parallax Scroll

CSS 滚动视差动画 2

OK,下面第二个滚动视差动画,也非常的有意思,想看看原版,也是来自于 wheatup 的 CodePen:

CodePen Demo -- 3D Chat Viewer

这里核心还是借助了 CSS 3D 的能力,但是由于使用的是滚动触发动画效果,并且有一定的从模糊到清晰的渐现效果,因此还是有一定的 JavaScript 代码。

感兴趣的可以看看上述的源码。

本文将尝试使用 CSS @Property 和 CSS 最新的特性 @scroll-timeline 还原该效果借助 JavaScript 实现的部分。

当然,首先不管是否需要借助 JavaScript,核心的 3D 部分使用的都是 CSS。

我们首先需要这样一个结构:

<div>
    <div>
        <div></div>
        <div></div>
        // ... 重复 N 个
    </div>
</div>
.g-wrapper {
    width: 100vw;
    height: 100vh;
}
.g-inner {
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
}
.g-item {
    width: 300px;
    height: 100px;
    background: #000;
}

大概是这个效果:

然后,我们添加一些 CSS 3D 变换:

.g-wrapper {
    // ... 与上述代码保持一致
    perspective: 200px;
    transform-style: preserve-3d;
}
.g-inner {
    // ... 与上述代码保持一致
    transform-style: preserve-3d;
    transform: translateY(calc(-50% + 100px)) translateZ(0) rotateX(90deg);
    transform-origin: bottom center;
}

就能得到这样一种视角的效果:

由于容器 g-inner 进行了一个绕 X 轴的 90deg 翻转,也就是 rotateX(90deg),所以,我们再给 g-item 一个反向的旋转,把卡片翻转回来:

.g-wrapper {
    // ... 与上述代码保持一致
    perspective: 200px;
    transform-style: preserve-3d;
}
.g-inner {
    // ... 与上述代码保持一致
    transform-style: preserve-3d;
    transform: translateY(calc(-50% + 100px)) translateZ(0) rotateX(90deg);
    transform-origin: bottom center;
}
.g-item {
    // ... 与上述代码保持一致
    transform: rotateX(-90deg);
}

就能得到这样一种视角的效果:

此时,我们给容器一个赋予一个 translateZ 的动画:

.g-inner {
    animation: move 10s infinite linear;
}
@keyframes move {
    100% {
        transform: translateY(calc(-50% + 100px)) translateZ(calc(100vh + 120px)) rotateX(90deg);
    }
}

这样,整个动画的雏形就完成了,通过控制父元素的 perspective 大小和容器的 translateZ,得到了一种不断向视角面前位移的动画效果:

CodePen Demo -- CSS 3D Effect Demo

结合 CSS @scroll-timeline,利用 CSS 控制滚动与动画

那怎么利用 CSS 再把这个动画和滚动操作结合起来呢?

在前不久,我介绍过 CSS 的一个重磅特性 来了来了,它终于来了,动画杀手锏 @scroll-timeline,利用它可以实现 CSS 动画与滚动操作的结合,我们利用它改造一下代码:

<div></div>
<div>
    <div>
        <div>Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
        // ... 重复 N 个
    </div>
</div>
@property --phase {
  syntax: '<length>';
  inherits: false;
  initial-value: 15px;
}
.g-scroll {
    width: 100%;
    height: 1000vh;
}
.g-wrapper {
    position: fixed;
    width: 100vw;
    height: 100vh;
    perspective: 200px;
    transform-style: preserve-3d;
}
.g-inner {
    position: relative;
    height: 100%;
    // 省略一些 flex 布局代码,与上文一致
    transform-style: preserve-3d;
    transform: translateY(calc(-50% + 100px)) translateZ(var(--phase)) rotateX(90deg);
    transform-origin: bottom center;
    animation-name: move;
    animation-duration: 1s;
    animation-timeline: box-move;
}
.g-item {
    width: 300px;
    height: 200px;
    color: #fff;
    background: #000;
    transform: rotateX(-90deg);
}
@scroll-timeline box-move {
    source: selector("#g-scroll");
    orientation: "vertical";
}
@keyframes move {
    0% {
        --phase: 0;
    }
    100% {
        --phase: calc(100vh + 100px);
    }
}</length>

这里相比上述的 DEMO,主要添加了 @scroll-timeline 的代码,我们增加了一个超长容器 .g-scroll,并且把它的滚动动作使用 @scroll-timeline box-move {} 规则和 animation-timeline: box-move 绑定了起来,这样,我们可以使用滚动去触发 @keyframes move {} CSS 动画。

效果如下:

在原效果中,还有一些使用 JavaScript 结合滚动距离控制的模糊的变化,这个,我们使用 backdrop-filter: blur() 也可以简单模拟。我们再简单添加一层 g-mask

<div></div>
<div>
    <div></div>
    <div>
        <div>Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
        // ... 重复 N 个
    </div>
</div>
// 其他保持一致
.g-mask {
    position: fixed;
    width: 100vw;
    height: 100vh;
    backdrop-filter: blur(5px);
    transform: translateZ(0);
}

这样,基本就还原了原效果,并且,我们用且仅使用了 CSS:

CodePen Demo -- Pure CSS Scroll Animation 2(Chrome Only && Support ScrollTimeline)

总结一下

当然,本文后一个效果中,使用了非常多目前兼容性还非常差的 CSS 属性,尤其是 @scroll-timeline,仍然处于非常早期的阶段,兼容性一片红。但是不妨碍我们学习、感受 CSS 的美好。

要完全读懂本文,可能有一些前置知识需要了解,根据需要,你可以延伸阅读下:

好了,本文到此结束,希望对你有帮助 

原文地址:https://www.cnblogs.com/coco1s/p/16158555.html

Author: ChokCoco

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of CSS practical tips: Use parallax to achieve cool interactive effects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Draggin' and Droppin' in ReactDraggin' and Droppin' in ReactApr 17, 2025 am 11:52 AM

The React ecosystem offers us a lot of libraries that all are focused on the interaction of drag and drop. We have react-dnd, react-beautiful-dnd,

Fast SoftwareFast SoftwareApr 17, 2025 am 11:49 AM

There have been some wonderfully interconnected things about fast software lately.

Nested Gradients with background-clipNested Gradients with background-clipApr 17, 2025 am 11:47 AM

I can't say I use background-clip all that often. I'd wager it's hardly ever used in day-to-day CSS work. But I was reminded of it in a post by Stefan Judis,

Using requestAnimationFrame with React HooksUsing requestAnimationFrame with React HooksApr 17, 2025 am 11:46 AM

Animating with requestAnimationFrame should be easy, but if you haven’t read React’s documentation thoroughly then you will probably run into a few things

Need to scroll to the top of the page?Need to scroll to the top of the page?Apr 17, 2025 am 11:45 AM

Perhaps the easiest way to offer that to the user is a link that targets an ID on the element. So like...

The Best (GraphQL) API is One You WriteThe Best (GraphQL) API is One You WriteApr 17, 2025 am 11:36 AM

Listen, I am no GraphQL expert but I do enjoy working with it. The way it exposes data to me as a front-end developer is pretty cool. It's like a menu of

Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading IndicatorWeekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading IndicatorApr 17, 2025 am 11:26 AM

In this week's roundup, a handy bookmarklet for inspecting typography, using await to tinker with how JavaScript modules import one another, plus Facebook's

Various Methods for Expanding a Box While Preserving the Border RadiusVarious Methods for Expanding a Box While Preserving the Border RadiusApr 17, 2025 am 11:19 AM

I've recently noticed an interesting change on CodePen: on hovering the pens on the homepage, there's a rectangle with rounded corners expanding in the back.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools