Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Horizontal Scroll for Astro

Move content sideways as the user scrolls down the page.

Installation

bunx --bun shadcn@latest add @gnostic/horizontal-scroll
npx shadcn@latest add @gnostic/horizontal-scroll
pnpm dlx shadcn@latest add @gnostic/horizontal-scroll

Complete the Installation guide first. Then copy the component files below.

Install component packages

bun add @data-slot/core

Copy the files

src/components/ui/horizontal-scroll/index.ts
export { default as HorizontalScroll } from './horizontal-scroll.astro'
export type { HorizontalScrollProps } from './types.ts'
export { createHorizontalScroll } from './horizontal-scroll.ts'
export type { HorizontalScrollController } from './horizontal-scroll.ts'
src/components/ui/horizontal-scroll/horizontal-scroll.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { HorizontalScrollProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & HorizontalScrollProps

const {
  enabled = true,
  speed = 1,
  top = 0,
  minWidth = 768,
  viewportClass,
  trackClass,
  class: className,
  style,
  ...props
} = Astro.props

const offset = Number.isFinite(top) ? Math.max(0, top) : 0
const rootStyle =
  typeof style === "string"
    ? `--horizontal-scroll-top:${offset}px;${style}`
    : { "--horizontal-scroll-top": `${offset}px`, ...style }
---

<div
  {...props}
  data-slot="horizontal-scroll"
  data-disabled={!enabled || undefined}
  data-speed={Number.isFinite(speed) && speed > 0 ? speed : 1}
  data-min-width={Number.isFinite(minWidth) ? Math.max(0, minWidth) : 768}
  class={cn("block min-w-0", className)}
  style={rootStyle}
>
  <div
    data-slot="horizontal-scroll-viewport"
    class={cn("flex items-center", viewportClass)}
  >
    <div
      data-slot="horizontal-scroll-track"
      class={cn("flex w-full min-w-0 flex-col gap-6 *:shrink-0", trackClass)}
    >
      <slot />
    </div>
  </div>
</div>

<style>
  @media screen and (prefers-reduced-motion: no-preference) {
    [data-active] {
      height: var(--horizontal-scroll-height);
    }

    :is([data-active], [data-measuring])
      > [data-slot="horizontal-scroll-viewport"] {
      min-height: calc(100svh - var(--horizontal-scroll-top));
      overflow: clip;
    }

    [data-active] > [data-slot="horizontal-scroll-viewport"] {
      position: sticky;
      top: var(--horizontal-scroll-top);
    }

    :is([data-active], [data-measuring])
      > [data-slot="horizontal-scroll-viewport"]
      > [data-slot="horizontal-scroll-track"] {
      width: max-content;
      min-width: 100%;
      flex-direction: row;
    }

    [data-active]
      > [data-slot="horizontal-scroll-viewport"]
      > [data-slot="horizontal-scroll-track"] {
      translate: var(--horizontal-scroll-x, 0px) 0;
    }
  }
</style>

<script>
  import { create } from "./horizontal-scroll.ts"

  const controllers: ReturnType<typeof create> = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
src/components/ui/horizontal-scroll/horizontal-scroll.ts
import {
    clearRootBinding,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'

export interface HorizontalScrollController {
    destroy(): void
}

export function createHorizontalScroll(
    root: HTMLElement,
): HorizontalScrollController {
    const existing = getRootBinding<HorizontalScrollController>(
        root,
        '@gnostic/horizontal-scroll',
    )
    if (existing) return existing
    const events = new AbortController()
    const cleanup = setupHorizontalScroll(root, events.signal)
    const controller: HorizontalScrollController = {
        destroy() {
            if (events.signal.aborted) return
            events.abort()
            cleanup?.()
            clearRootBinding(root, '@gnostic/horizontal-scroll', controller)
        },
    }
    return setRootBinding(root, '@gnostic/horizontal-scroll', controller)
}

export function create(
    scope: ParentNode = document,
): HorizontalScrollController[] {
    return getRoots<HTMLElement>(scope, 'horizontal-scroll')
        .filter((root) => !hasRootBinding(root, '@gnostic/horizontal-scroll'))
        .map((root) => createHorizontalScroll(root))
}

const clamp = (value: number, max: number) => Math.max(0, Math.min(max, value))

function setupHorizontalScroll(
    root: HTMLElement,
    signal: AbortSignal,
): () => void {
    const viewport = root.querySelector<HTMLElement>(
        ':scope > [data-slot="horizontal-scroll-viewport"]',
    )
    const track = viewport?.querySelector<HTMLElement>(
        ':scope > [data-slot="horizontal-scroll-track"]',
    )
    if (
        !viewport ||
        !track ||
        root.hasAttribute('data-disabled') ||
        typeof ResizeObserver === 'undefined'
    )
        return () => {}

    const speed =
        Number(root.dataset.speed) > 0 ? Number(root.dataset.speed) : 1
    const minWidth = Math.max(0, Number(root.dataset.minWidth) || 0)
    const media = matchMedia(
        `(min-width: ${minWidth}px) and (prefers-reduced-motion: no-preference)`,
    )
    let frame = 0
    let measureNext = true
    let active = false
    let distance = 0
    let offset = 0
    let top = 0
    let rtl = false

    const reset = () => {
        active = false
        offset = 0
        root.removeAttribute('data-active')
        root.style.removeProperty('--horizontal-scroll-height')
        track.style.removeProperty('--horizontal-scroll-x')
    }
    const measure = () => {
        if (!media.matches) {
            reset()
            return
        }
        root.setAttribute('data-measuring', '')
        top =
            parseFloat(getComputedStyle(viewport).top) ||
            parseFloat(
                getComputedStyle(root).getPropertyValue(
                    '--horizontal-scroll-top',
                ),
            ) ||
            0
        rtl = getComputedStyle(viewport).direction === 'rtl'
        distance = Math.max(0, track.scrollWidth - viewport.clientWidth)
        const height = viewport.offsetHeight
        const fits = height <= window.innerHeight - top + 1
        if (distance > 1 && viewport.clientWidth > 0 && fits) {
            active = true
            root.style.setProperty(
                '--horizontal-scroll-height',
                `${height + distance / speed}px`,
            )
            root.setAttribute('data-active', '')
        } else {
            reset()
        }
        root.removeAttribute('data-measuring')
    }
    const paint = () => {
        if (!active) return
        offset = clamp(
            (top - root.getBoundingClientRect().top) * speed,
            distance,
        )
        track.style.setProperty(
            '--horizontal-scroll-x',
            `${rtl ? offset : -offset}px`,
        )
    }
    const update = () => {
        frame = 0
        if (signal.aborted) return
        if (measureNext) {
            measureNext = false
            measure()
        }
        paint()
    }
    const schedule = () => {
        if (!frame && !signal.aborted) frame = requestAnimationFrame(update)
    }
    const resize = () => {
        measureNext = true
        schedule()
    }
    const reveal = (target: Element) => {
        if (!active || !track.contains(target)) return
        const view = viewport.getBoundingClientRect()
        const rect = target.getBoundingClientRect()
        const delta =
            rect.left < view.left
                ? rect.left - view.left
                : rect.right > view.right
                  ? rect.right - view.right
                  : 0
        const next = clamp(offset + (rtl ? -delta : delta), distance)
        const start = root.getBoundingClientRect().top + window.scrollY - top
        const end = start + distance / speed
        if (delta || window.scrollY < start || window.scrollY > end) {
            window.scrollTo({ top: start + next / speed, behavior: 'instant' })
            paint()
        }
    }
    const revealHash = () => {
        let id: string
        try {
            id = decodeURIComponent(window.location.hash.slice(1))
        } catch {
            return
        }
        const target = id && document.getElementById(id)
        if (target) reveal(target)
    }
    const observer = new ResizeObserver(resize)
    const observeSizes = () => {
        if (signal.aborted) return
        observer.observe(viewport)
        observer.observe(track)
        for (const child of track.children) observer.observe(child)
    }
    observeSizes()
    const mutations = new MutationObserver(() => {
        if (signal.aborted) return
        observer.disconnect()
        observeSizes()
        resize()
    })
    mutations.observe(track, {
        childList: true,
        subtree: true,
        characterData: true,
    })

    window.addEventListener('scroll', schedule, {
        passive: true,
        signal: signal,
    })
    window.addEventListener('resize', resize, { signal: signal })
    window.addEventListener('hashchange', revealHash, { signal: signal })
    media.addEventListener('change', resize, { signal: signal })
    track.addEventListener('load', resize, {
        capture: true,
        signal: signal,
    })
    track.addEventListener(
        'focusin',
        (event) => {
            if (event.target instanceof Element) reveal(event.target)
        },
        { signal: signal },
    )

    frame = requestAnimationFrame(() => {
        update()
        const focused = document.activeElement
        if (focused && track.contains(focused)) reveal(focused)
        else revealHash()
    })

    return () => {
        cancelAnimationFrame(frame)
        observer.disconnect()
        mutations.disconnect()
        reset()
    }
}
src/components/ui/horizontal-scroll/types.ts
/** Props for a horizontal effect driven by page scrolling. */
export interface HorizontalScrollProps {
    /** Enable the effect when the viewport and motion settings permit it. @default true */
    enabled?: boolean
    /** Horizontal pixels moved per vertical scroll pixel. Must be positive. @default 1 */
    speed?: number
    /** Space above the sticky viewport, in pixels. @default 0 */
    top?: number
    /** Minimum browser width for the effect, in pixels. @default 768 */
    minWidth?: number
    /** Classes for the sticky viewport, such as its background color. */
    viewportClass?: string
    /** Classes for the content row, such as gap and padding. */
    trackClass?: string
}

Usage

---
import { HorizontalScroll } from "@/components/ui/horizontal-scroll"
---

<HorizontalScroll role="region" aria-label="Project stages" top={80}>
  <article class="w-80 max-w-full">Plan the work</article>
  <article class="w-96 max-w-full">Build the first version</article>
  <article class="w-80 max-w-full">Share the result</article>
</HorizontalScroll>

Supply your own content in the default slot. Each direct child is an item in the row. Set its width with classes. Items can have different widths. Use max-w-full to keep items within the page width in the vertical layout.

This is a UI effect. It supplies scroll behavior and accepts any content. A block can compose it with headings, cards, and other section content. Use ScrollArea for a box with native scrolling, or Carousel for slides with controls.

Flex-basis sizing

You can also size the direct children with flex-basis utilities, as you would with Carousel. Use basis-full for one item per view, basis-1/2 for two, or basis-1/3 for three. Responsive utilities can change that count.

Percentage bases use the track’s inner width, excluding its padding. A separate gap adds to those widths. For exact divisions, use trackClass="gap-0" and put spacing inside each item wrapper:

<HorizontalScroll trackClass="gap-0">
  {["Planning", "Design", "Build", "Support"].map((title) => (
    <article class="w-full min-w-0 basis-full p-3 md:basis-1/2 lg:basis-1/3">
      <h3>{title}</h3>
      <p>Details for this service.</p>
    </article>
  ))}
</HorizontalScroll>

Use fixed widths when the cards need different sizes. Flex-basis is another option; it does not change the scroll effect or its vertical fallback.

Image cards

Put an image above the card heading, description, and service details. This example uses the reusable Horizontal Scroll features block. The component and block pages render the same block and sample content. Install @gnostic/features-horizontal-scroll to use this complete section.

Page scrolling

The component measures the row and adds the required vertical space. Its viewport stays in place while the row moves sideways. At the end of the row, the next page section comes into view. Scrolling up reverses the effect.

The page keeps its normal scroll controls. Mouse wheels, touch gestures, keyboard scrolling, and the page scrollbar all use the same scroll position. The component does not cancel wheel or touch events. There are no inner scrollbars or animation dependencies.

Set top to leave space for a fixed header. The default speed={1} moves one horizontal pixel for each vertical scroll pixel. A value of 2 halves the vertical distance needed to pass through the row.

The example uses a separate preview document so its page can scroll. It sets minWidth={0} to show the effect at each preview width. The component default is 768 pixels.

Layout and access

The content uses a vertical layout when JavaScript is unavailable, reduced motion is selected, the browser is below minWidth, or enabled={false}. It also uses this layout when the row fits without horizontal movement or the content is too tall for the viewport. Print output uses the vertical layout.

Keyboard focus brings an item into view. Links to IDs within the row also bring their target into view. The factory measures content again after size changes. The component initializes on script load and astro:page-load, then destroys its controller on astro:before-swap. If your code adds or removes an instance directly, call createHorizontalScroll(root) to attach it and controller.destroy() before removing it. Import the factory from the component index.

Use this component in the page document, outside nested scroll areas. Sticky positioning needs ancestors without overflow: auto, scroll, or hidden. Use overflow: clip when an ancestor must clip content. Do not nest horizontal scroll effects.

The root accepts native attributes, classes, and styles. Keep its height, vertical padding, and borders free for the scroll calculation. Put section spacing on an outer wrapper. viewportClass can set the pinned surface color. trackClass sets row spacing and padding:

<HorizontalScroll
  top={64}
  speed={1.5}
  viewportClass="bg-muted/40"
  trackClass="gap-8 px-6 py-10"
>
  <slot />
</HorizontalScroll>

Colors and fonts come from your content and the selected project preset.

API Reference

PropType
enabled?boolean

Enable the effect when the viewport and motion settings permit it.

Typeboolean
Defaulttrue
speed?number

Horizontal pixels moved per vertical scroll pixel. Must be positive.

Typenumber
Default1
top?number

Space above the sticky viewport, in pixels.

Typenumber
Default0
minWidth?number

Minimum browser width for the effect, in pixels.

Typenumber
Default768
viewportClass?string

Classes for the sticky viewport, such as its background color.

Typestring
trackClass?string

Classes for the content row, such as gap and padding.

Typestring

Native attributes such as id, class, role, and aria-label are supported. Read the installed source.