View function
Learn visibility-based animation with the view() function.
What does the view() function do?
The view() function binds the animation to the element's position in the viewport. As the element enters, passes through, or leaves the viewport, the animation progresses. This differs from scroll(), which uses the container's scroll position.
For example, a card fades from dim to vivid as it enters the viewport. This effect used to require JavaScript with IntersectionObserver; now it is possible with CSS alone.
Arguments of view()
The view() function takes two arguments: axis and inset. The axis can be block or inline; default is block.
The inset shrinks or expands the visibility box by a length or percentage. For example, view(block 20%) starts the animation when the element has moved 20% into the viewport from the top edge.
Naming with view-timeline-name
Sometimes you want to define a timeline on one element and bind it to another. You give the target element a name with view-timeline-name. Then on the animated element you set animation-timeline to that name.
For example, to track an image you write view-timeline-name: photo; then on another element you use animation-timeline: photo to consume the timeline. One timeline can drive several elements in sync.
Exercise Reveal-on-enter animation with view()
Write two blocks. First, an @keyframes block (any name) containing from and to keyframes. Second, a CSS block for any selector; this block must contain the animation-timeline: view() declaration.
Show example solution
/* card that reveals on enter */
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}
.card {
animation: 1s linear fade;
animation-timeline: view();
}
Test yourself
-
What does the view() function base the animation on?
- The document-wide scroll position
- The mouse pointer position
- The element's position in the viewport
- The document timeline
Show answer
The element's position in the viewport — Correct. The view() function progresses based on the element's position in the viewport.
-
Write the inset value
/* 15% inside the viewport */ animation-timeline: view(block ____);Show answer
/* 15% inside the viewport */ animation-timeline: view(block 15%);