---
title: Horizontal Scroll for Astro
description: Move content sideways as the user scrolls down the page.
seo:
    title: Horizontal Scroll | Shadcn & Tailwind CSS for Astro
    description: Move content sideways as the user scrolls down the page. Built for Astro with Shadcn & Tailwind CSS.
related:
    - /components/reveal
    - /components/scroll-area
    - /components/carousel
    - Features blocks: /blocks/features#horizontal-scroll
sidebar:
    label: Horizontal Scroll
    badge: new
---

```astro
---
// @preview render=frame
import { HorizontalScroll } from "@/components/ui/horizontal-scroll"
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  CardFooter,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"

const projects = [
  {
    title: "A place to start",
    description: "Give the first idea room to grow.",
    number: "01",
  },
  {
    title: "A closer look",
    description: "Find the details that make it useful.",
    number: "02",
  },
  {
    title: "A new direction",
    description: "Build on what you learn along the way.",
    number: "03",
  },
  {
    title: "Ready to share",
    description: "Bring the finished work into view.",
    number: "04",
  },
]
---

<div class="w-full min-w-0">
  <header class="flex min-h-48 flex-col justify-center gap-3 px-6 py-10">
    <p class="text-sm text-muted-foreground">Selected projects</p>
    <h2 class="text-3xl font-medium tracking-tight">
      Keep scrolling to explore.
    </h2>
    <p class="max-w-lg text-muted-foreground">
      The page moves down, the projects move sideways, and the next section
      follows.
    </p>
  </header>
  <HorizontalScroll
    role="region"
    aria-label="Selected projects"
    minWidth={0}
    viewportClass="bg-muted/40"
    trackClass="gap-6 p-6"
  >
    {projects.map((project) => (
      <Card class="w-[min(26rem,75cqi)] @max-sm:basis-full max-w-full">
        <CardHeader>
          <CardTitle>{project.title}</CardTitle>
          <CardDescription>{project.description}</CardDescription>
        </CardHeader>
        <CardContent>
          <div
            class="flex h-36 items-end rounded-lg bg-secondary p-5 text-7xl font-medium tracking-tighter text-secondary-foreground"
            aria-hidden="true"
          >
            {project.number}
          </div>
        </CardContent>
        <CardFooter>
          <Button as="a" href="#after-projects" variant="outline">
            Continue reading
          </Button>
        </CardFooter>
      </Card>
    ))}
  </HorizontalScroll>
  <section
    id="after-projects"
    class="flex min-h-64 flex-col justify-center gap-3 px-6 py-10"
  >
    <h2 class="text-2xl font-medium tracking-tight">Back to the page.</h2>
    <p class="text-muted-foreground">
      Scroll up to move through the projects in reverse.
    </p>
  </section>
</div>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/horizontal-scroll
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/core
```

#### src/components/ui/horizontal-scroll/index.ts

```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

```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

```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

```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
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
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:

```astro
<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](/blocks/features#horizontal-scroll).
The component and block pages render the same block and sample content.
Install `@gnostic/features-horizontal-scroll` to use this complete section.

```astro
---
// @preview render=frame
import FeaturesHorizontalScroll from "@/components/blocks/features/features-horizontal-scroll/features-horizontal-scroll.astro"
import { horizontalScrollFeatures } from "../../blocks/features/features-horizontal-scroll-data.ts"
---

<FeaturesHorizontalScroll {...horizontalScrollFeatures} minWidth={0} />
```

## 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:

```astro
<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

<AutoTypeTable
    path="../../packages/ui/src/components/ui/horizontal-scroll/types.ts"
    name="HorizontalScrollProps"
/>

Native attributes such as `id`, `class`, `role`, and `aria-label` are supported.
Read the [installed source](/r/horizontal-scroll.json).
