Scroll drift
effect · scroll · text · T1 · v1.0.0 · readyAbout
Moves its content from one offset to another, horizontally or vertically, as the element scrolls through its view range. One technique for several looks: giant type sliding sideways, the two halves of a title drifting apart (opposite offsets), images at different depths (different distances). An outer box is measured and never moves; only the content inside it is translated.
Scroll the page.
Layers
- Native
- Scroll-driven animations
- JS
- Engines without view() timelines: the scroll-progress primitive writes the same progress.
- Static
- The content at its layout position.
Browser support (native layer)
- Scroll-driven animations: Baseline low · chrome 115, chrome_android 115, edge 115, firefox 159, firefox_android 159, safari 26, safari_ios 26 · Firefox reportedly needs a non-zero animation-duration.
Samsung Internet: Chromium-based; not tracked by web-features.
Skin
| Variable | Default | Meaning |
|---|---|---|
--scroll-drift-from | 0px | Offset at the start of the range; the `from` prop overrides it per instance. |
--scroll-drift-to | -20vw | Offset at the end of the range; the `to` prop overrides it per instance. |
Accessibility
Static layer: the content stays at its layout position.
Movement follows the scroll position only (no motion without scrolling). Keep distances moderate: large parallax offsets can trigger vestibular discomfort.
Sources
- reel · thedesignshop.tds · "Staggered Scroll" and "Controlled Parallax" reels; technique only (P6).
Code
Self-contained: copy every file, keeping the folder structure.
mechanism.module.css/* web-effects scroll-drift 1.0.0 · MIT-0 */
/* Mechanism of the scroll drift (D2.8, D3.11), shared by both styling variants.
Driver / renderer split (D2.7): .root's progress through its view range (0–1) lives in
--_scroll-drift-progress. L1: a native view() timeline animates it on .root. L2: the
scroll-progress driver writes it inline (data-layer="js"). L3: no transform. .root is the
measured box and never moves; .drift, inside it, translates from `from` to `to` along the
axis, so the movement cannot feed back into the measurement. */
@property --_scroll-drift-progress {
syntax: "<number>";
inherits: true;
initial-value: 0;
}
.root {
--_scroll-drift-from: var(--scroll-drift-from, 0px);
--_scroll-drift-to: var(--scroll-drift-to, -20vw);
display: block;
}
.drift {
display: block;
--_scroll-drift-offset: calc(
var(--_scroll-drift-from) +
(var(--_scroll-drift-to) - var(--_scroll-drift-from)) *
var(--_scroll-drift-progress)
);
--_scroll-drift-transform: translateX(var(--_scroll-drift-offset));
}
.root[data-axis="y"] .drift {
--_scroll-drift-transform: translateY(var(--_scroll-drift-offset));
}
@keyframes progress {
from {
--_scroll-drift-progress: 0;
}
to {
--_scroll-drift-progress: 1;
}
}
/* L1 native (gated on the override attribute, D3.6a). The `animation` shorthand resets the
range, so each range is set after it. */
@supports (animation-timeline: view()) {
:root:not([data-fx-layer]) .root,
:root[data-fx-layer="native"] .root {
animation: progress 1s linear both;
animation-timeline: view();
animation-range: cover;
}
:root:not([data-fx-layer]) .root[data-range="contain"],
:root[data-fx-layer="native"] .root[data-range="contain"] {
animation-range: contain;
}
:root:not([data-fx-layer]) .root[data-range="exit-crossing"],
:root[data-fx-layer="native"] .root[data-range="exit-crossing"] {
animation-range: exit-crossing;
}
:root:not([data-fx-layer]) .drift,
:root[data-fx-layer="native"] .drift {
transform: var(--_scroll-drift-transform);
}
}
/* L2 JS driver. */
.root[data-layer="js"] .drift {
transform: var(--_scroll-drift-transform);
}
/* L3 under reduced motion: no drift. */
@media (prefers-reduced-motion: reduce) {
:root:not([data-fx-layer]) .root {
animation: none;
}
:root:not([data-fx-layer]) .drift {
transform: none;
}
}
primitives/frame-scheduler/scheduler.ts// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.
export type FrameTask = {
/** Measure the DOM. Runs before every write of the same frame. */
read?: (time: number) => void;
/** Mutate the DOM (styles, custom properties). */
write?: (time: number) => void;
};
export type FrameScheduler = {
/** Runs `task` every frame until the returned function is called. */
loop: (task: FrameTask) => () => void;
/** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
once: (task: FrameTask) => () => void;
};
type FrameApi = {
request: (callback: (time: number) => void) => number;
cancel: (handle: number) => void;
};
// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
request: (callback) => requestAnimationFrame(callback),
cancel: (handle) => cancelAnimationFrame(handle),
};
export function createScheduler(
frames: FrameApi = browserFrames,
): FrameScheduler {
const looping = new Set<FrameTask>();
const pending = new Set<FrameTask>();
let handle: number | null = null;
const tick = (time: number) => {
handle = null;
const tasks = [...looping, ...pending];
pending.clear();
for (const task of tasks) task.read?.(time);
for (const task of tasks) task.write?.(time);
if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
};
const start = () => {
if (handle === null) handle = frames.request(tick);
};
const stopIfIdle = () => {
if (handle !== null && looping.size === 0 && pending.size === 0) {
frames.cancel(handle);
handle = null;
}
};
return {
loop(task) {
looping.add(task);
start();
return () => {
looping.delete(task);
stopIfIdle();
};
},
once(task) {
pending.add(task);
start();
return () => {
pending.delete(task);
stopIfIdle();
};
},
};
}
/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();
primitives/layer-select/layer.ts// web-effects layer-select 1.0.0 · MIT-0
// Browser side of layer selection: reads the current inputs and notifies on change.
// Framework-free, for plain-browser hosts; use-layer.ts wraps it for React.
import {
layerAttribute,
parseLayer,
selectLayer,
type Layer,
} from "./select-layer";
const reducedMotionQuery = "(prefers-reduced-motion: reduce)";
/**
* The layer for an item whose native layer needs `supports` (an `@supports` condition, the same
* text as in the item's CSS), or null when the item has no native layer.
*/
export function currentLayer(
supports: string | null,
prerequisitesMet = true,
): Layer {
return selectLayer({
nativeSupported: supports !== null && CSS.supports(supports),
reducedMotion: matchMedia(reducedMotionQuery).matches,
prerequisitesMet,
override: parseLayer(document.documentElement.getAttribute(layerAttribute)),
});
}
/** Calls `onChange` when reduced motion or the forced override changes. Returns a stop function. */
export function watchLayerInputs(onChange: () => void): () => void {
const media = matchMedia(reducedMotionQuery);
media.addEventListener("change", onChange);
const observer = new MutationObserver(onChange);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: [layerAttribute],
});
return () => {
media.removeEventListener("change", onChange);
observer.disconnect();
};
}
primitives/layer-select/select-layer.ts// web-effects layer-select 1.0.0 · MIT-0
// Layer selection (D2.4, D3.6). CSS decides on its own: `@supports` enables L1, and the base
// rules are the L3 static state, so server-rendered HTML works without JS. JavaScript only
// decides whether to mount an L2 driver; this is that decision, as a pure function.
//
// Forced override (R6.1): an attribute on <html>. Item CSS honours it by writing native-layer
// and reduced-motion rules as `:root:not([data-fx-layer]) .x, :root[data-fx-layer="native"] .x`.
// The showcase sets the attribute from `?driver=`; items never read the host's URL.
export const layers = ["native", "js", "static"] as const;
export type Layer = (typeof layers)[number];
export const layerAttribute = "data-fx-layer";
export function parseLayer(value: string | null | undefined): Layer | null {
return layers.find((layer) => layer === value) ?? null;
}
export type LayerInputs = {
/** The item's `@supports` condition holds; false for items without a native layer. */
nativeSupported: boolean;
reducedMotion: boolean;
/** Inputs the effect cannot work without (e.g. a fine pointer) are present. */
prerequisitesMet: boolean;
/** Forced layer from the `data-fx-layer` attribute; wins over everything else. */
override: Layer | null;
};
export function selectLayer({
nativeSupported,
reducedMotion,
prerequisitesMet,
override,
}: LayerInputs): Layer {
if (override) return override;
if (reducedMotion || !prerequisitesMet) return "static";
return nativeSupported ? "native" : "js";
}
primitives/layer-select/use-layer.ts// web-effects layer-select 1.0.0 · MIT-0
import { useCallback, useSyncExternalStore } from "react";
import { currentLayer, watchLayerInputs } from "./layer";
import type { Layer } from "./select-layer";
/**
* The active layer, or null during server rendering and hydration (CSS alone decides until then).
* Mount the L2 driver when this returns "js".
*/
export function useLayer(
supports: string | null,
prerequisitesMet = true,
): Layer | null {
const getSnapshot = useCallback(
() => currentLayer(supports, prerequisitesMet),
[supports, prerequisitesMet],
);
return useSyncExternalStore(watchLayerInputs, getSnapshot, () => null);
}
primitives/scroll-progress/scroll-progress.ts// web-effects scroll-progress 1.0.0 · MIT-0
// L2 scroll-progress driver: writes the `view()` progress of an element into a custom property
// (D2.7). Measures on scroll and resize through the shared scheduler (one read and one write per
// frame at most) and stops measuring while the element is off-screen (D3.9), after writing its
// final clamped value.
import { frameScheduler } from "../frame-scheduler/scheduler";
import { viewProgress, type ViewRange } from "./view-progress";
export type ScrollProgressOptions = {
/** Custom property to write, the item's private name, e.g. "--_card-stack-progress" (D2.19). */
property: string;
range?: ViewRange;
/**
* The element's nearest scroll container, as CSS `view()` would pick it. Omit for the page.
* Not detected automatically: pass it when the subject scrolls inside another element.
*/
scroller?: HTMLElement;
};
/**
* The scroller's scrollport (padding box minus a horizontal scrollbar) in viewport coordinates.
* Fractional on purpose: clientTop/clientHeight round to whole pixels, while view() uses the
* exact box (a 0.5 px rounding error measurably shifted progress against native).
*/
function scrollport(scroller: HTMLElement): { top: number; height: number } {
const rect = scroller.getBoundingClientRect();
const style = getComputedStyle(scroller);
const borderTop = Number.parseFloat(style.borderTopWidth);
const borderBottom = Number.parseFloat(style.borderBottomWidth);
const scrollbar = Math.max(
0,
scroller.offsetHeight -
scroller.clientHeight -
Math.round(borderTop + borderBottom),
);
return {
top: rect.top + borderTop,
height: rect.height - borderTop - borderBottom - scrollbar,
};
}
export function trackScrollProgress(
element: HTMLElement,
{ property, range = "cover", scroller }: ScrollProgressOptions,
): () => void {
let progress = Number.NaN;
let written = Number.NaN;
let visible = true;
const task = {
read() {
const rect = element.getBoundingClientRect();
const port = scroller
? scrollport(scroller)
: { top: 0, height: document.documentElement.clientHeight };
progress = viewProgress(range, {
top: rect.top - port.top,
height: rect.height,
viewport: port.height,
});
},
write() {
if (progress === written) return;
element.style.setProperty(property, String(progress));
written = progress;
},
};
const request = () => {
if (visible) frameScheduler.once(task);
};
const cancelPending = frameScheduler.once(task);
const observer = new IntersectionObserver(
([entry]) => {
visible = entry.isIntersecting;
// One measurement on every visibility change, so leaving the viewport writes 0 or 1.
frameScheduler.once(task);
},
{ root: scroller ?? null },
);
observer.observe(element);
const target: HTMLElement | Window = scroller ?? window;
target.addEventListener("scroll", request, { passive: true });
window.addEventListener("resize", request, { passive: true });
return () => {
cancelPending();
observer.disconnect();
target.removeEventListener("scroll", request);
window.removeEventListener("resize", request);
element.style.removeProperty(property);
};
}
primitives/scroll-progress/use-scroll-progress.ts// web-effects scroll-progress 1.0.0 · MIT-0
import { useEffect, type RefObject } from "react";
import { trackScrollProgress } from "./scroll-progress";
import type { ViewRange } from "./view-progress";
/** Runs the L2 driver on `ref` while `enabled` (typically `useLayer(...) === "js"`). */
export function useScrollProgress(
ref: RefObject<HTMLElement | null>,
{
enabled,
property,
range = "cover",
scroller,
}: {
enabled: boolean;
property: string;
range?: ViewRange;
scroller?: RefObject<HTMLElement | null>;
},
) {
useEffect(() => {
const element = ref.current;
if (!enabled || !element) return;
return trackScrollProgress(element, {
property,
range,
scroller: scroller?.current ?? undefined,
});
}, [ref, enabled, property, range, scroller]);
}
primitives/scroll-progress/view-progress.ts// web-effects scroll-progress 1.0.0 · MIT-0
// Progress of a subject through its scrollport, matching the CSS `view()` timeline (block
// axis, no inset) for the `cover`, `contain` and `exit-crossing` ranges. The L2 driver writes this value so
// that item CSS renders identically on L1 (native timeline) and L2 (D2.7).
export const viewRanges = ["cover", "contain", "exit-crossing"] as const;
export type ViewRange = (typeof viewRanges)[number];
export type ViewGeometry = {
/** Subject's top edge, relative to the scrollport's top edge, in px. */
top: number;
/** Subject's height in px. */
height: number;
/** Scrollport's height in px. */
viewport: number;
};
/**
* 0 at the start of the range, 1 at its end, clamped. Positions are expressed as the subject's
* top edge: progress grows as `top` decreases (content scrolls up).
* cover: from the subject's top at the scrollport's bottom (top = viewport)
* to its bottom at the scrollport's top (top = -height).
* contain: from the subject fully inside, or fully covering, the scrollport for the first time
* to the last time; when it is exactly as tall as the scrollport the range is a point.
* exit-crossing: from the subject's top at the scrollport's top (top = 0) to its bottom there
* (top = -height); progress follows scroll distance over the subject's own height.
*/
export function viewProgress(
range: ViewRange,
{ top, height, viewport }: ViewGeometry,
): number {
const [start, end] = rangeEdges(range, height, viewport);
if (start === end) return top > start ? 0 : 1;
return Math.min(Math.max((start - top) / (start - end), 0), 1);
}
/** Range start and end, as values of the subject's `top`. */
function rangeEdges(
range: ViewRange,
height: number,
viewport: number,
): [number, number] {
switch (range) {
case "cover":
return [viewport, -height];
case "contain":
return [Math.max(viewport - height, 0), Math.min(viewport - height, 0)];
case "exit-crossing":
return [0, -height];
}
}
tailwind/ScrollDrift.tsx// web-effects scroll-drift 1.0.0 · MIT-0
"use client";
import type { ReactNode } from "react";
import type { ViewRange } from "../primitives/scroll-progress/view-progress";
import mechanism from "../mechanism.module.css";
import { useScrollDrift } from "../use-scroll-drift";
/**
* Moves `children` from `from` to `to` (CSS lengths) along `axis` while the box scrolls through
* `range`. Without `from` / `to`, the skin variables apply. Sideways drift: clip the overflow in
* the host (e.g. `overflow-x: clip` on a wrapper).
*/
export function ScrollDrift({
children,
axis = "x",
range = "cover",
from,
to,
className = "",
}: {
children: ReactNode;
axis?: "x" | "y";
range?: ViewRange;
from?: string;
to?: string;
className?: string;
}) {
const { rootProps } = useScrollDrift({ axis, range, from, to });
return (
<div {...rootProps} className={`${mechanism.root} ${className}`}>
<div className={mechanism.drift}>{children}</div>
</div>
);
}
use-scroll-drift.ts// web-effects scroll-drift 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "./primitives/layer-select/use-layer";
import type { ViewRange } from "./primitives/scroll-progress/view-progress";
import { useScrollProgress } from "./primitives/scroll-progress/use-scroll-progress";
// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. `from` and `to` override the skin per instance by
// setting the private aliases inline (an inline value beats the mechanism's alias declaration).
export function useScrollDrift({
axis,
range,
from,
to,
}: {
axis: "x" | "y";
range: ViewRange;
from?: string;
to?: string;
}) {
const ref = useRef<HTMLDivElement>(null);
// Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
const driven = useLayer("(animation-timeline: view())") === "js";
useScrollProgress(ref, {
enabled: driven,
property: "--_scroll-drift-progress",
range,
});
const style: Record<string, string> = {};
if (from !== undefined) style["--_scroll-drift-from"] = from;
if (to !== undefined) style["--_scroll-drift-to"] = to;
return {
rootProps: {
ref,
"data-layer": driven ? "js" : undefined,
"data-axis": axis,
"data-range": range,
style: style as CSSProperties,
},
};
}