찾다
웹 프론트엔드CSS 튜토리얼스크롤 타임 라인이있는 CSS의 스크롤 연결 애니메이션에 대한 실제 사용 사례

Practical Use Cases for Scroll-Linked Animations in CSS with Scroll Timelines

The Scroll-Linked Animations specification is an upcoming and experimental addition to CSS. Thanks to the @scroll-timeline at-rule and animation-timeline property this specification provides, you can control the time position of regular CSS Animations by scrolling.

In this post, we’ll take a look at some practical use cases where scroll-linked animations come in handy, and how they can enrich your visitor’s browsing experience.

?‍? The CSS features described in this post are still experimental and not finalized at all. They are not supported by any browser at the time of writing, except for Chromium ≥ 89 with the “Experimental Web Platform Features” flag enabled.

CSS Scroll-Linked Animations, a quick primer

With the features described in the Scroll-Linked Animations specification you can drive a CSS animation by scroll: as you scroll down or up a scroll container, the linked CSS animation will advance or rewind accordingly. These scroll-linked animations can add a very nice touch to your pages.

While several JavaScript libraries to implement these Scroll-Linked Animations already do exist, the Scroll-Linked Animations specification distinguishes itself from them by:

  1. providing both a JS and CSS interface to implement these effects
  2. keeping things performant, as the animations will run on the compositor (e.g. “off main thread”)

While the Scroll-Linked Animations specification also describes a JavaScript interface that integrates nicely with the Web Animations API, the focus of this post will be on its CSS counterpart only.

To implement a basic scroll-linked animation in CSS you need three key parts:

  1. a CSS animation
  2. a scroll timeline
  3. a link between both

CSS animation

This is a regular CSS Animation like we already know:

@keyframes adjust-progressbar {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

As you normally do, attach it to an element using the animation property:

#progressbar {
  animation: 1s linear forwards adjust-progressbar;
}

Scroll timeline

The scroll timeline allows us to map the scroll distance to the animation progress. In CSS, we describe this with the CSS @scroll-timeline at-rule.

@scroll-timeline scroll-in-document-timeline {
  source: auto;
  orientation: vertical;
  scroll-offsets: 0%, 100%;
}

Besides giving the scroll timeline a name, it can be configured using several descriptors:

  1. The source describes the scrollable element whose scrolling triggers the activation and drives the progress of the timeline. By default, this is the entire document (value: auto)
  2. The orientation determines the scrolling direction that should trigger the animation. By default, this is vertical.
  3. The scroll-offsets property is an array of key points that describe the range in which the animation should be active. Those offsets can be relative/absolute values (e.g. percentages and lengths) or element-based offsets.

A previous version of the specification required you to also set a time-range descriptor. This descriptor has been removed and will automatically take over the animation-duration from the linked animation. You may still see traces of this descriptor in the demos, but you can safely ignore it.

To associate our @scroll-timeline with our CSS animation, we use the new animation-timeline CSS property, and have it refer to the timeline’s name.

#progressbar {
  animation: 1s linear forwards adjust-progressbar;
  animation-timeline: scroll-in-document-timeline;
}

With that set up the adjust-progressbar animation won’t run by itself on page load, but will only advance as we scroll down the page.

For a more in-depth introduction to @scroll-timeline please refer to Part 1 and Part 2 of my series on Scroll-Linked Animations.

The first post looks at each descriptor in more detail, explaining them with an example to go along with them, before covering many more interesting demos.

The second post digs even deeper, looking into Element-Based Offsets, which allow us to drive an animation as an element appears into and disappears from the scrollport as we scroll.

Practical use cases

Apart from the progress bar demo above, there are a few more use cases or scenarios for these Scroll-Linked Animations.

  1. parallax header
  2. image reveal/hide
  3. typing animation
  4. carousel indicators
  5. scrollspy

Parallax header

The most classic use case for Scroll-Linked Animations is a parallax effect, where several sections of a page seem to have a different scrolling speed. There’s a way to create these type of effects using only CSS, but that requires mind-bending transform hacks involving translate-z() and scale().

Inspired upon the Firewatch Header—which uses the mentioned transform hack—I created this version that uses a CSS scroll timeline:

Compared to the original demo:

  • The markup was kept, except for that extra .parallax__cover that’s no longer needed.
  • The was given a min-height to create some scroll-estate.
  • The positioning of the .parallax element and its .parallax_layer child elements was tweaked.
  • The transform/perspective-hack was replaced with a scroll timeline.

Each different layer uses the same scroll timeline: scroll over a distance of 100vh.

@scroll-timeline scroll-for-100vh {
  scroll-offsets: 0, 100vh;
}

.parallax__layer {
  animation: 1s parallax linear;
  animation-timeline: scroll-for-100vh;
}

What’s different between layers is the distance that they move as we scroll down:

  • The layer at the back should stay in place, eg. move for 0vh.
  • The foremost layer should should move the fastest, e.g. 100vh.
  • All layers in between are interpolated.
@keyframes parallax {
  to {
    transform: translateY(var(--offset));
  }
}

.parallax__layer__0 {
  --offset: 100vh;
}

.parallax__layer__1 {
  --offset: 83vh;
}

.parallax__layer__2 {
  --offset: 67vh;
}

.parallax__layer__3 {
  --offset: 50vh;
}

.parallax__layer__4 {
  --offset: 34vh;
}

.parallax__layer__5 {
  --offset: 17vh;
}

.parallax__layer__6 {
  --offset: 0vh;
}

As the foremost layers move over a greater distance, they appear to move faster than the lower layers, achieving the parallax effect.

Image reveal/hide

Another great use-case for scroll-linked animations is an image reveal: as an image slides into view, it will reveal itself.

By default, the image is given an opacity of 0 and is masked using a clip-path:

#revealing-image {
  opacity: 0;
  clip-path: inset(45% 20% 45% 20%);
}

In the end-state we want the image to be fully visible, so we sent the end-frame of our animation to reflect that:

@keyframes reveal {
  to {
    clip-path: inset(0% 0% 0% 0%);
    opacity: 1;
  }
}

By using element-based offsets as the offsets for our scroll timeline, we can have our reveal animation only start when the image itself slides into view.

@scroll-timeline revealing-image-timeline {
  scroll-offsets:
    selector(#revealing-image) end 0.5,
    selector(#revealing-image) end 1
  ;
}

#revealing-image {
  animation: reveal 1s linear forwards;
  animation-timeline: revealing-image-timeline;
}

? Can’t follow with those element-based offsets? This visualization/tool has got you covered.

Typing animation

As CSS scroll timelines can be linked to any existing CSS animation, you can take any CSS Animation demo and transform it. Take this typing animation for example:

With the addition of a scroll timeline and the animation-timeline property, it can be adjusted to “type on scroll”:

Note that to create some scroll-estate the

was also given a height of 300vh.

Using a different animation, the code above can easily be adjusted to create a zoom on scroll effect:

I can see these two working great for article intros.

One of the components of a carousel (aka slider) is an indicator that exposes how many slides it contains, as well as which slide is currently active. This is typically done using bullets.

This again is something we will be able to achieve using a CSS scroll timeline, as shown in this demo created by Fabrizio Calderan:

The active state bullet is injected via .slider nav::before and has an animation set that moves it over the other bullets

/* Styling of the dots */
.slider nav::before, .slider a {
  inline-size: 1rem;
  aspect-ratio: 1;
  border-radius: 50%;
  background: #9bc;
}

/* Positioning of the active dot */
.slider nav::before {
  content: "";
  position: absolute;
  z-index: 1;
  display: block;
  cursor: not-allowed;
  transform: translateX(0);
  animation: dot 1s steps(1, end) 0s forwards;
}

/* Position over time of the active dot */
@keyframes dot {
  0% 
    { transform: translateX(0); }
  33% 
    { transform: translateX(calc((100% + var(--gap)) * 1)); }
  66% 
    { transform: translateX(calc((100% + var(--gap)) * 2)); } 
  100% 
    { transform: translateX(calc((100% + var(--gap)) * 3)); }
}

By attaching a @scroll-timeline onto the slider, the dot that indicates the active state can move as you scroll:

@scroll-timeline slide {
  source: selector(#s);
  orientation: inline; 
}

.slider nav::before {
  /* etc. */
  animation-timeline: slide;
}

The dot only moves after the slide has snapped to its position thanks to the inclusion of a steps() function in the animation. When removing it, it becomes more clear how the dot moves as you scroll

? This feels like the final missing piece to Christian Shaefer’s CSS-only carousel.

ScrollSpy

Back in early 2020, I created a sticky table of contents with scrolling active states. The final part to creating the demo was to use IntersectionObserver to set the active states in the table of contents (ToC) as you scroll up/down the document.

Unlike the carousel indicators demo from above we can’t simply get there by moving a single dot around, as it’s the texts in the ToC that get adjusted. To approach this situation, we need to attach two animations onto each element in the ToC:

  1. The first animation is to visually activate the ToC item when the proper section comes into view at the bottom edge of the document.
  2. The second animation is to visually deactivate the ToC item when the proper section slides out of view at the top edge of the document.
.section-nav li > a {
  animation:
    1s activate-on-enter linear forwards,
    1s deactivate-on-leave linear forwards;
}

As we have two animations, we also need to create two scroll timelines, and this for each section of the content. Take the #introduction section for example:

@scroll-timeline section-introduction-enter {
  scroll-offsets:
    selector(#introduction) end 0,
    selector(#introduction) end 1;
}

@scroll-timeline section-introduction-leave {
  scroll-offsets:
    selector(#introduction) start 1,
    selector(#introduction) start 0;
}

Once both of these timelines are linked to both animations, everything will work as expected:

.section-nav li > a[href"#introduction"] {
  animation-timeline:
    section-introduction-enter,
    section-introduction-leave;
}

In closing

I hope I have convinced you of the potential offered by the Scroll-linked Animations specification.

Unfortunately, it’s only supported in Chromium-based browsers right now, hidden behind a flag. Given this potential, I personally hope that—once the specification settles onto a final syntax—other browser vendors will follow suit.

If you too would like to see Scroll-Linked Animations land in other browsers, you can actively star/follow the relevant browser issues.

  • Chromium
  • Firefox
  • Safari

By actively starring issues, us developers can signal our interest into these features to browser vendors.

위 내용은 스크롤 타임 라인이있는 CSS의 스크롤 연결 애니메이션에 대한 실제 사용 사례의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
CSS 애니메이션 : 만들기가 어렵습니까?CSS 애니메이션 : 만들기가 어렵습니까?May 09, 2025 am 12:03 AM

cssanimationsarenherinly에 hardbutreepracticenderstandingofcsspropertiesandtimingflestions.1) startsimpleants withsimpleatslikeScalingabuttononHoverusingKeyframes.2) useAsingfuctionslikecubic-bezierfornateffects, 그러한 분위기, 3)

@keyframes CSS : 가장 많이 사용되는 트릭@keyframes CSS : 가장 많이 사용되는 트릭May 08, 2025 am 12:13 AM

@keyframesispopularduetoitstativerstatility 및 powerincreatingsmoothcssanimations.keytricksinclude : 1) states 사이에 moothtransitionsbettites, 2) 애니메이션 multiplepropertiessimultory, 3) vendorPixesforBrowsercompatibility, 4) 빗질을 사용하여

CSS 카운터 : 자동 번호 매기기에 대한 포괄적 인 안내서CSS 카운터 : 자동 번호 매기기에 대한 포괄적 인 안내서May 07, 2025 pm 03:45 PM

csScounterSearedTomanageAutomaticNumberingInberingInwebDesigns.1) 1) theCanbeusedfortablestoffContents, ListItems 및 CustomNumbering.2) AdvancedUsesInSinestedNumberingsystems.3) CreativeUseNvolvecust를 CreativeSinvolecust.4) CreativeSinvolvecust

스크롤 구동 애니메이션을 사용한 현대 스크롤 그림자스크롤 구동 애니메이션을 사용한 현대 스크롤 그림자May 07, 2025 am 10:34 AM

특히 모바일 장치에 스크롤 그림자를 사용하는 것은 Chris가 이전에 다룬 미묘한 UX입니다. Geoff는 애니메이션 타임 라인 속성을 사용하는 새로운 접근 방식을 다루었습니다. 또 다른 방법이 있습니다.

이미지 맵 재 방문이미지 맵 재 방문May 07, 2025 am 09:40 AM

빠른 새로 고침을 통해 실행합시다. 이미지 맵은 html 3.2로 돌아가는데, 먼저 서버 측 맵과 클라이언트 측지 맵은 맵 및 영역 요소를 사용하여 이미지를 통해 클릭 가능한 영역을 정의했습니다.

DEVS 상태 : 모든 개발자를위한 설문 조사DEVS 상태 : 모든 개발자를위한 설문 조사May 07, 2025 am 09:30 AM

Devs State Survey는 이제 참여에 개방되어 있으며, 이전 설문 조사와 달리 코드, 직장, 건강, 취미 등을 제외한 모든 것을 포함합니다. 

CSS 그리드는 무엇입니까?CSS 그리드는 무엇입니까?Apr 30, 2025 pm 03:21 PM

CSS 그리드는 복잡하고 반응이 좋은 웹 레이아웃을 만드는 강력한 도구입니다. 디자인을 단순화하고 접근성을 향상 시키며 이전 방법보다 더 많은 제어를 제공합니다.

CSS Flexbox 란 무엇입니까?CSS Flexbox 란 무엇입니까?Apr 30, 2025 pm 03:20 PM

기사는 반응 형 설계에서 공간의 효율적인 정렬 및 분포를위한 레이아웃 방법 인 CSS Flexbox에 대해 설명합니다. Flexbox 사용을 설명하고 CSS 그리드와 비교하고 브라우저 지원 세부 사항을 설명합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구