---
title: Scroll Area for Astro
description: "Native scrolling for Astro panels, with custom tracks, keyboard access, and optional edge fades."
sidebar:
    label: "Scroll Area"
    badge: new
seo:
    title: Scroll Area for Astro | Shadcn & Tailwind CSS
related:
    - /components/table
    - /components/dialog
---

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  scrollFade
  aria-label="Project files"
  class="max-h-64 w-72 rounded-lg border"
>
  <ul class="divide-border divide-y px-4">
    {Array.from({ length: 16 }, (_, index) => (
      <li class="py-3 text-sm">Project file {index + 1}</li>
    ))}
  </ul>
</ScrollArea>
```

## Installation

### Command

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

### Manual

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

No extra packages are required.

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

```ts
export { default as ScrollArea } from './scroll-area.astro'
export { default as ScrollAreaRoot } from './scroll-area-root.astro'
export { default as ScrollAreaViewport } from './scroll-area-viewport.astro'
export { default as ScrollAreaContent } from './scroll-area-content.astro'
export {
    default as ScrollAreaScrollbar,
    default as ScrollBar,
} from './scroll-area-scrollbar.astro'
export { default as ScrollAreaThumb } from './scroll-area-thumb.astro'
export { default as ScrollAreaCorner } from './scroll-area-corner.astro'
export type { ScrollAreaOptions } from './types'
export { createScrollArea } from './scroll-area.ts'
export type { ScrollAreaController } from './scroll-area.ts'
```

#### src/components/ui/scroll-area/scroll-area-content.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="scroll-area-content"
  class={cn(
    "flow-root min-w-fit",
    "[:where([data-clamp-content])>*>&]:min-w-0 [:where([data-fill])>*>&]:size-full",
    className,
  )}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/scroll-area/scroll-area-corner.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="scroll-area-corner"
  aria-hidden="true"
  class={cn(
    "pointer-events-none absolute inset-e-0 bottom-0 size-2.5",
    "[:where(:not([data-enhanced]))>&]:hidden [&[hidden]]:hidden",
    className,
  )}
  {...props}
></div>
```

#### src/components/ui/scroll-area/scroll-area.ts

```ts
const rootSelector = '[data-slot="scroll-area"]'
const controllers = new WeakMap<HTMLElement, ScrollAreaController>()

export interface ScrollAreaController {
    destroy(): void
}

export function createScrollArea(root: HTMLElement): ScrollAreaController {
    const existing = controllers.get(root)
    if (existing) return existing
    const events = new AbortController()
    const cleanup = setupScrollArea(root, events.signal)
    const controller: ScrollAreaController = {
        destroy() {
            if (events.signal.aborted) return
            events.abort()
            cleanup?.()
            controllers.delete(root)
        },
    }
    controllers.set(root, controller)
    return controller
}

export function create(scope: ParentNode = document): ScrollAreaController[] {
    const roots = [...scope.querySelectorAll<HTMLElement>(rootSelector)]
    if (scope instanceof HTMLElement && scope.matches(rootSelector))
        roots.unshift(scope)
    return roots
        .filter((root) => !controllers.has(root))
        .map((root) => createScrollArea(root))
}

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

function setupScrollArea(root: HTMLElement, signal: AbortSignal) {
    const viewport = root.querySelector<HTMLElement>(
        ':scope > [data-slot="scroll-area-viewport"]',
    )
    const content = viewport?.querySelector<HTMLElement>(
        ':scope > [data-slot="scroll-area-content"]',
    )
    if (!viewport || !content) return

    const bars = [
        ...root.querySelectorAll<HTMLElement>(
            ':scope > [data-slot="scroll-area-scrollbar"]',
        ),
    ].flatMap((track) => {
        const thumb = track.querySelector<HTMLElement>(
            ':scope > [data-slot="scroll-area-thumb"]',
        )
        return thumb
            ? [
                  {
                      track,
                      thumb,
                      horizontal: track.dataset.orientation === 'horizontal',
                  },
              ]
            : []
    })
    // Keep native controls if a manual composition has no scrollbar for an enabled axis.
    const direction = root.dataset.orientation ?? 'vertical'
    const complete =
        (direction === 'horizontal' || bars.some((bar) => !bar.horizontal)) &&
        (direction === 'vertical' || bars.some((bar) => bar.horizontal))
    const corner = root.querySelector<HTMLElement>(
        ':scope > [data-slot="scroll-area-corner"]',
    )
    let frame = 0
    let scrollTimer: ReturnType<typeof setTimeout> | undefined
    let drag:
        | {
              track: HTMLElement
              pointerId: number
              horizontal: boolean
              offset: number
          }
        | undefined

    const measure = () => {
        const maxX = Math.max(0, viewport.scrollWidth - viewport.clientWidth)
        const maxY = Math.max(0, viewport.scrollHeight - viewport.clientHeight)
        const rtl = getComputedStyle(viewport).direction === 'rtl'
        const x = clamp(rtl ? -viewport.scrollLeft : viewport.scrollLeft, maxX)
        const y = clamp(viewport.scrollTop, maxY)
        return { maxX, maxY, rtl, x, y }
    }
    const update = () => {
        if (signal.aborted) return
        frame = 0
        const { maxX, maxY, rtl, x, y } = measure()
        const hasX = direction !== 'vertical' && maxX > 1
        const hasY = direction !== 'horizontal' && maxY > 1
        for (const element of [root, viewport]) {
            element.toggleAttribute('data-has-overflow-x', hasX)
            element.toggleAttribute('data-has-overflow-y', hasY)
            element.toggleAttribute('data-overflow-x-start', hasX && x > 1)
            element.toggleAttribute('data-overflow-x-end', hasX && maxX - x > 1)
            element.toggleAttribute('data-overflow-y-start', hasY && y > 1)
            element.toggleAttribute('data-overflow-y-end', hasY && maxY - y > 1)
        }
        const distances = {
            left: hasX ? (rtl ? maxX - x : x) : 0,
            right: hasX ? (rtl ? x : maxX - x) : 0,
            top: hasY ? y : 0,
            bottom: hasY ? maxY - y : 0,
        }
        for (const [edge, value] of Object.entries(distances)) {
            viewport.style.setProperty(`--scroll-area-${edge}`, `${value}px`)
        }
        if (corner) corner.hidden = !hasX || !hasY
        for (const { track, thumb, horizontal } of bars) {
            track.hidden = horizontal ? !hasX : !hasY
            if (track.hidden) continue
            const length = horizontal ? track.clientWidth : track.clientHeight
            const visible = horizontal
                ? viewport.clientWidth
                : viewport.clientHeight
            const total = horizontal
                ? viewport.scrollWidth
                : viewport.scrollHeight
            const size = Math.min(
                length,
                Math.max(18, (length * visible) / total),
            )
            const progress = horizontal
                ? maxX
                    ? x / maxX
                    : 0
                : maxY
                  ? y / maxY
                  : 0
            const position =
                (length - size) * (horizontal && rtl ? 1 - progress : progress)
            thumb.style.width = horizontal ? `${size}px` : '100%'
            thumb.style.height = horizontal ? '100%' : `${size}px`
            // Position from the physical left edge, including in RTL layouts.
            thumb.style.position = 'absolute'
            thumb.style.left = '0'
            thumb.style.top = '0'
            thumb.style.transform = horizontal
                ? `translateX(${position}px)`
                : `translateY(${position}px)`
        }
    }
    const schedule = () => {
        if (!signal.aborted && !frame) frame = requestAnimationFrame(update)
    }
    const onScroll = () => {
        root.setAttribute('data-scrolling', '')
        clearTimeout(scrollTimer)
        scrollTimer = setTimeout(
            () => root.removeAttribute('data-scrolling'),
            150,
        )
        schedule()
    }
    const move = (event: PointerEvent) => {
        if (!drag || event.pointerId !== drag.pointerId) return
        const { track, horizontal, offset } = drag
        const thumb = track.querySelector<HTMLElement>(
            '[data-slot="scroll-area-thumb"]',
        )!
        const rect = track.getBoundingClientRect()
        const thumbRect = thumb.getBoundingClientRect()
        const length = horizontal ? rect.width : rect.height
        const size = horizontal ? thumbRect.width : thumbRect.height
        const position =
            (horizontal
                ? event.clientX - rect.left
                : event.clientY - rect.top) - offset
        const progress =
            length > size ? clamp(position, length - size) / (length - size) : 0
        const { maxX, maxY, rtl } = measure()
        if (horizontal)
            viewport.scrollLeft = rtl ? -(1 - progress) * maxX : progress * maxX
        else viewport.scrollTop = progress * maxY
        schedule()
    }
    const release = () => {
        if (drag?.track.hasPointerCapture(drag.pointerId))
            drag.track.releasePointerCapture(drag.pointerId)
        drag = undefined
        root.removeAttribute('data-dragging')
    }
    for (const { track, thumb, horizontal } of bars) {
        track.addEventListener(
            'pointerdown',
            (event) => {
                if (event.button !== 0 || !event.isPrimary || drag) return
                event.preventDefault()
                const rect = thumb.getBoundingClientRect()
                const onThumb =
                    event.target instanceof Node && thumb.contains(event.target)
                const offset = onThumb
                    ? horizontal
                        ? event.clientX - rect.left
                        : event.clientY - rect.top
                    : (horizontal ? rect.width : rect.height) / 2
                drag = {
                    track,
                    pointerId: event.pointerId,
                    horizontal,
                    offset,
                }
                viewport.focus({ preventScroll: true })
                track.setPointerCapture(event.pointerId)
                root.setAttribute('data-dragging', '')
                if (!onThumb) move(event)
            },
            { signal: signal },
        )
        track.addEventListener('pointermove', move, {
            signal: signal,
        })
        for (const type of [
            'pointerup',
            'pointercancel',
            'lostpointercapture',
        ]) {
            track.addEventListener(type, release, { signal: signal })
        }
        // The overlaid track is outside the native viewport's wheel event path.
        track.addEventListener(
            'wheel',
            (event) => {
                if (event.ctrlKey) return
                const unit =
                    event.deltaMode === 1
                        ? 16
                        : event.deltaMode === 2
                          ? viewport.clientHeight
                          : 1
                const beforeX = viewport.scrollLeft
                const beforeY = viewport.scrollTop
                if (horizontal)
                    viewport.scrollLeft +=
                        (event.deltaX ||
                            (getComputedStyle(viewport).direction === 'rtl'
                                ? -event.deltaY
                                : event.deltaY)) * unit
                else viewport.scrollTop += event.deltaY * unit
                if (
                    beforeX !== viewport.scrollLeft ||
                    beforeY !== viewport.scrollTop ||
                    root.hasAttribute('data-overscroll-contain')
                )
                    event.preventDefault()
            },
            { passive: false, signal: signal },
        )
    }
    viewport.addEventListener('scroll', onScroll, {
        passive: true,
        signal: signal,
    })
    viewport.addEventListener('load', schedule, {
        capture: true,
        signal: signal,
    })
    const resize = new ResizeObserver(schedule)
    const observe = () => {
        if (signal.aborted) return
        resize.disconnect()
        for (const element of [
            viewport,
            content,
            ...content.children,
            ...bars.map((bar) => bar.track),
        ])
            resize.observe(element)
        schedule()
    }
    const mutations = new MutationObserver(observe)
    mutations.observe(content, {
        childList: true,
        subtree: true,
        characterData: true,
    })
    root.toggleAttribute('data-enhanced', complete)
    observe()
    cancelAnimationFrame(frame)
    update()
    return () => {
        resize.disconnect()
        mutations.disconnect()
        cancelAnimationFrame(frame)
        clearTimeout(scrollTimer)
        release()
        root.removeAttribute('data-enhanced')
        root.removeAttribute('data-scrolling')
    }
}
```

#### src/components/ui/scroll-area/scroll-area-root.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { ScrollAreaOptions } from "./types.ts"

type Props = HTMLAttributes<"div"> & ScrollAreaOptions

const {
  class: className,
  orientation = "vertical",
  scrollFade = false,
  scrollbarGutter = false,
  fill = false,
  clampContentMinWidth = true,
  overscrollContain = false,
  ...props
} = Astro.props
---

<div
  data-slot="scroll-area"
  data-orientation={orientation}
  data-scroll-fade={scrollFade ? "" : undefined}
  data-scrollbar-gutter={scrollbarGutter ? "" : undefined}
  data-fill={fill ? "" : undefined}
  data-clamp-content={clampContentMinWidth ? "" : undefined}
  data-overscroll-contain={overscrollContain ? "" : undefined}
  class={cn(
    "relative grid min-h-0 min-w-0 max-h-[inherit] grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)] rounded-[inherit]",
    "[--scroll-area-bar-size:6px] [--scroll-area-bar-inset:4px] [--scroll-area-fade-size:1.5rem]",
    className,
  )}
  {...props}
>
  <slot />
</div>

<script>
  import { create } from "./scroll-area.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/scroll-area/scroll-area-scrollbar.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import ScrollAreaThumb from "./scroll-area-thumb.astro"

type Props = HTMLAttributes<"div"> & {
  orientation?: "vertical" | "horizontal"
}
const { class: className, orientation = "vertical", ...props } = Astro.props
---

<div
  data-slot="scroll-area-scrollbar"
  data-orientation={orientation}
  aria-hidden="true"
  class={cn(
    "absolute z-1 touch-none select-none opacity-0 transition-opacity delay-300 duration-150 ease-[ease] motion-reduce:transition-none",
    "[:where(:not([data-enhanced]))>&]:hidden [&[hidden]]:hidden",
    "[:where(:hover,:focus-within,[data-scrolling],[data-dragging])>&]:opacity-100 [:where(:hover,:focus-within,[data-scrolling],[data-dragging])>&]:duration-100 [:where(:hover,:focus-within,[data-scrolling],[data-dragging])>&]:delay-0",
    "data-[orientation=vertical]:inset-y-(--scroll-area-bar-inset) data-[orientation=vertical]:end-(--scroll-area-bar-inset) data-[orientation=vertical]:w-(--scroll-area-bar-size)",
    "data-[orientation=horizontal]:inset-x-(--scroll-area-bar-inset) data-[orientation=horizontal]:bottom-(--scroll-area-bar-inset) data-[orientation=horizontal]:h-(--scroll-area-bar-size)",
    "[:where([data-has-overflow-x])>&]:data-[orientation=vertical]:bottom-[calc(var(--scroll-area-bar-size)+2*var(--scroll-area-bar-inset))]",
    "[:where([data-has-overflow-y])>&]:data-[orientation=horizontal]:end-[calc(var(--scroll-area-bar-size)+2*var(--scroll-area-bar-inset))]",
    className,
  )}
  {...props}
>
  <slot>
    <ScrollAreaThumb />
  </slot>
</div>
```

#### src/components/ui/scroll-area/scroll-area-thumb.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="scroll-area-thumb"
  class={cn(
    "relative size-full rounded-full bg-foreground/20 forced-colors:bg-[CanvasText]",
    className,
  )}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/scroll-area/scroll-area-viewport.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, role, tabindex = 0, ...props } = Astro.props
const hasLabel = Boolean(props["aria-label"] || props["aria-labelledby"])
---

<div
  data-slot="scroll-area-viewport"
  tabindex={tabindex}
  role={role ?? (hasLabel ? "region" : undefined)}
  class={cn(
    "min-h-0 min-w-0 rounded-[inherit] outline-none transition-shadow focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
    "overflow-auto [scrollbar-width:thin] [scrollbar-color:var(--muted-foreground)_transparent]",
    "[:where([data-orientation=vertical])>&]:overflow-x-hidden [:where([data-orientation=horizontal])>&]:overflow-y-hidden",
    "[:where([data-enhanced])>&]:[scrollbar-width:none] [:where([data-enhanced])>&]:[&::-webkit-scrollbar]:hidden",
    "[:where([data-scrollbar-gutter]:not([data-orientation=horizontal]))>&]:pe-[calc(var(--scroll-area-bar-size)+var(--scroll-area-bar-inset))]",
    "[:where([data-scrollbar-gutter]:not([data-orientation=vertical]))>&]:pb-[calc(var(--scroll-area-bar-size)+var(--scroll-area-bar-inset))]",
    "[:where([data-overscroll-contain][data-has-overflow-y])>&]:overscroll-y-contain [:where([data-overscroll-contain][data-has-overflow-x])>&]:overscroll-x-contain",
    "[--scroll-area-mask-x:linear-gradient(to_right,transparent,black_min(var(--scroll-area-fade-size),var(--scroll-area-left)),black_calc(100%_-_min(var(--scroll-area-fade-size),var(--scroll-area-right))),transparent)]",
    "[--scroll-area-mask-y:linear-gradient(to_bottom,transparent,black_min(var(--scroll-area-fade-size),var(--scroll-area-top)),black_calc(100%_-_min(var(--scroll-area-fade-size),var(--scroll-area-bottom))),transparent)]",
    "[:where([data-enhanced][data-scroll-fade])>&]:[mask-image:var(--scroll-area-mask-x),var(--scroll-area-mask-y)] [:where([data-enhanced][data-scroll-fade])>&]:mask-intersect",
    className,
  )}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/scroll-area/scroll-area.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import type { ScrollAreaOptions } from "./types"
import ScrollAreaRoot from "./scroll-area-root.astro"
import ScrollAreaViewport from "./scroll-area-viewport.astro"
import ScrollAreaContent from "./scroll-area-content.astro"
import ScrollAreaScrollbar from "./scroll-area-scrollbar.astro"
import ScrollAreaCorner from "./scroll-area-corner.astro"

type Props = HTMLAttributes<"div"> &
  ScrollAreaOptions & {
    viewportProps?: HTMLAttributes<"div">
  }

const {
  "aria-label": label,
  "aria-labelledby": labelledBy,
  "aria-describedby": describedBy,
  role,
  tabindex,
  viewportProps,
  ...props
} = Astro.props
---

<ScrollAreaRoot {...props}>
  <ScrollAreaViewport
    aria-label={label}
    aria-labelledby={labelledBy}
    aria-describedby={describedBy}
    role={role}
    tabindex={tabindex ?? 0}
    {...viewportProps}
  >
    <ScrollAreaContent>
      <slot />
    </ScrollAreaContent>
  </ScrollAreaViewport>
  <ScrollAreaScrollbar />
  <ScrollAreaScrollbar orientation="horizontal" />
  <ScrollAreaCorner />
</ScrollAreaRoot>
```

#### src/components/ui/scroll-area/types.ts

```ts
/** Options for `ScrollArea` and `ScrollAreaRoot`. */
export interface ScrollAreaOptions {
    /**
     * Allowed scroll directions.
     * @default 'vertical'
     */
    orientation?: 'vertical' | 'horizontal' | 'both'
    /**
     * Fade edges that have more content.
     * @default false
     */
    scrollFade?: boolean
    /**
     * Reserve space for the enabled scrollbars.
     * @default false
     */
    scrollbarGutter?: boolean
    /**
     * Size the content wrapper to fill the viewport.
     * @default false
     */
    fill?: boolean
    /**
     * Allow the content wrapper to shrink to the viewport width.
     * @default true
     */
    clampContentMinWidth?: boolean
    /**
     * Contain scroll input on overflowing axes.
     * @default false
     */
    overscrollContain?: boolean
}
```

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 { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea aria-label="Project files" class="max-h-64 rounded-md border">
  <div class="p-4">Your content</div>
</ScrollArea>
```

The component uses 6px tracks, rounded thumbs at 20% foreground opacity,
and scrollbars that appear
on hover, keyboard focus, or scrolling. The focus ring uses the current theme.

Astro renders the component parts. A small client script measures overflow and
handles thumb dragging and track clicks. The viewport uses native wheel, touch,
and keyboard scrolling. Browser scrollbars remain available when JavaScript is off.

## Component parts

`ScrollArea` assembles the parts. Use `ScrollAreaRoot` when you need direct control:

```astro
---
import {
  ScrollAreaRoot,
  ScrollAreaViewport,
  ScrollAreaContent,
  ScrollAreaScrollbar,
  ScrollAreaThumb,
  ScrollAreaCorner,
} from "@/components/ui/scroll-area"
---

<ScrollAreaRoot orientation="both" class="h-64 w-80 rounded-md border">
  <ScrollAreaViewport aria-label="Project files">
    <ScrollAreaContent class="p-4">Your content</ScrollAreaContent>
  </ScrollAreaViewport>
  <ScrollAreaScrollbar><ScrollAreaThumb /></ScrollAreaScrollbar>
  <ScrollAreaScrollbar orientation="horizontal"><ScrollAreaThumb /></ScrollAreaScrollbar>
  <ScrollAreaCorner />
</ScrollAreaRoot>
```

Keep the viewport, scrollbars, and corner as direct children of the root.
Keep the content as a direct child of the viewport. Each scrollbar contains one
thumb. `ScrollAreaScrollbar` supplies a thumb when its default slot is empty.
`ScrollBar` is an alias for `ScrollAreaScrollbar`.

```astro
---
import {
  ScrollAreaRoot,
  ScrollAreaViewport,
  ScrollAreaContent,
  ScrollAreaScrollbar,
  ScrollAreaThumb,
  ScrollAreaCorner,
} from "@/components/ui/scroll-area"
---

<ScrollAreaRoot orientation="both" class="h-56 w-80 rounded-md border">
  <ScrollAreaViewport aria-label="Custom scroll area">
    <ScrollAreaContent class="p-4">
      <div class="flex w-max flex-col gap-3 text-sm">
        {Array.from({ length: 16 }, (_, i) => (
          <p>Row {i + 1}: This longer line can scroll in both directions.</p>
        ))}
      </div>
    </ScrollAreaContent>
  </ScrollAreaViewport>
  <ScrollAreaScrollbar>
    <ScrollAreaThumb class="bg-primary/40" />
  </ScrollAreaScrollbar>
  <ScrollAreaScrollbar orientation="horizontal">
    <ScrollAreaThumb class="bg-primary/40" />
  </ScrollAreaScrollbar>
  <ScrollAreaCorner />
</ScrollAreaRoot>
```

## Examples

### Scroll fade

Set `scrollFade` to fade an edge only when there is more content beyond it.
Change `--scroll-area-fade-size` to adjust the fade length. Its default is `1.5rem`.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  scrollFade
  class="max-h-64 w-72 rounded-md border"
  aria-label="Activity"
>
  <ul class="flex flex-col gap-4 p-4 text-sm">
    {Array.from({ length: 16 }, (_, i) => (
      <li>Activity {i + 1}: The project is ready for review.</li>
    ))}
  </ul>
</ScrollArea>
```

### Horizontal scrolling

Use `orientation="horizontal"` with content wider than the viewport.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  orientation="horizontal"
  aria-label="Project stages"
  class="w-80 rounded-lg border"
>
  <ol class="flex w-max gap-4 p-4">
    {["Plan", "Design", "Build", "Review", "Release"].map((stage, index) => (
      <li class="bg-muted flex w-36 shrink-0 flex-col gap-2 rounded-md p-4">
        <span class="text-muted-foreground text-sm">Step {index + 1}</span>
        <span class="font-medium">{stage}</span>
      </li>
    ))}
  </ol>
</ScrollArea>
```

### Both scrollbars

Use `orientation="both"`. The corner keeps the two tracks apart.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  orientation="both"
  scrollbarGutter
  class="h-64 w-80 rounded-md border"
  aria-label="Grid of cells"
>
  <div class="grid w-max grid-cols-8 gap-2 p-4">
    {Array.from({ length: 80 }, (_, i) => (
      <div class="bg-muted flex size-16 items-center justify-center rounded-md text-sm">
        {i + 1}
      </div>
    ))}
  </div>
</ScrollArea>
```

### Scrollbar space and containment

`scrollbarGutter` reserves space inside the viewport for each enabled axis. The
space remains when content is short, so the content width does not change when
scrollbars appear. `overscrollContain` stops scrolling from passing to a parent
scroller when the viewport reaches an edge. It applies only on overflowing axes.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  scrollbarGutter
  overscrollContain
  class="max-h-64 w-72 rounded-md border"
  aria-label="Notifications"
>
  <ul class="flex flex-col gap-4 p-4 text-sm">
    {Array.from({ length: 12 }, (_, i) => (
      <li>Notification {i + 1}: A new file is available.</li>
    ))}
  </ul>
</ScrollArea>
```

### Fill the viewport

Use `fill` for a flex column with a footer at the bottom. Keep its default value
for lists whose height follows their content.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<ScrollArea
  fill
  class="h-64 w-72 rounded-md border"
  aria-label="Project summary"
>
  <div class="flex h-full flex-col gap-4 p-4 text-sm">
    <p>Current project</p>
    <p class="text-muted-foreground">The content fills the viewport.</p>
    <footer class="text-muted-foreground mt-auto">Last updated today</footer>
  </div>
</ScrollArea>
```

## Set the height

Put size classes on `ScrollArea` or `ScrollAreaRoot`. Use `max-h-64` to let short
content keep its natural height and scroll when it exceeds 16rem. Use `h-64`
when the container must always be 16rem high. Put content padding on a child.

### Inherit a maximum height

The root uses `max-height: inherit` by default. This works when its direct parent
has a maximum height such as `max-h-48`. The viewport fits inside the root.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<div class="max-h-48 w-72 rounded-lg border">
  <ScrollArea aria-label="Recent updates">
    <ul class="flex flex-col gap-3 p-4 text-sm">
      {Array.from({ length: 12 }, (_, index) => (
        <li>Update {index + 1}: Content is ready for review.</li>
      ))}
    </ul>
  </ScrollArea>
</div>
```

`inherit` copies the parent's computed `max-height`. It does not copy `height`,
search other ancestors, or calculate space below a header. If the parent has no
maximum height, the inherited value is `none`. A percentage still needs a definite
containing block height. Parent padding and borders can reduce the available space.
Use `max-h-none` to remove an inherited limit.

See [MDN's max-height reference](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/max-height).

### Use the remaining panel space

Give the parent a height and `flex flex-col`. Set `flex-1` on `ScrollArea` to use
space below a header. The root and viewport have `min-h-0`, so they can shrink
below their content height. Intermediate flex or grid items can also need `min-h-0`.

```astro
---
import { ScrollArea } from "@/components/ui/scroll-area"
---

<section class="flex h-64 w-72 flex-col rounded-lg border">
  <h3 id="scroll-area-tasks" class="shrink-0 border-b p-4 font-medium">
    Tasks
  </h3>
  <ScrollArea aria-labelledby="scroll-area-tasks" class="flex-1">
    <ul class="divide-border divide-y px-4">
      {Array.from({ length: 16 }, (_, index) => (
        <li class="py-3 text-sm">Review task {index + 1}</li>
      ))}
    </ul>
  </ScrollArea>
</section>
```

## Keyboard access

Give `ScrollArea` an `aria-label` or `aria-labelledby`. These attributes, `role`,
`aria-describedby`, and `tabindex` pass to the viewport. In a manual composition,
put them on `ScrollAreaViewport`. A named viewport has `role="region"` by default.
Focus the viewport to use native arrow keys, Page Up, and Page Down. Custom tracks
are hidden from assistive technology; the viewport supplies keyboard access.

## API Reference

`ScrollArea` and `ScrollAreaRoot` accept these options:

### ScrollAreaOptions

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

`ScrollArea` also accepts `viewportProps` for native viewport attributes and classes.
Other native attributes and `class` apply to the root. Each part accepts native
div attributes and a default slot, except the empty corner. The root renders a
custom HTML element. All parts use Astro `class` and slots.

`ScrollAreaScrollbar` accepts `orientation="vertical"` (default) or `"horizontal"`.
`ScrollAreaViewport` has `tabindex="0"` by default. The content wrapper uses
`min-width: 0` unless `clampContentMinWidth={false}` is set. Horizontal content
should declare its width, for example with `w-max`.

Read the [installed source](/ui/r/scroll-area.json) for the component source.

## When to use Scroll Area

Use a Scroll Area when a bounded list or panel must scroll independently of the page. Set its height or maximum height and put padding inside its content. Without a size limit, the container can grow with the content and has no reason to scroll. For horizontal content, give the child a width such as `w-max`. Keep one clear scroll region in each panel when possible. For most prose pages, ordinary page scrolling is easier to use.

## Keyboard and behavior

The HTML root keeps a native scroll viewport. A factory attaches the scrollbar behavior. Wheel, touch, and keyboard scrolling use the browser. Its script measures overflow and moves the custom thumbs; it does not replace the viewport with a simulated scroller. Give the viewport a useful name and keep its focus outline visible. With scripts off, the browser scrollbar remains available.

## Theme and layout

Track and thumb colors follow the foreground token. Check contrast over tinted surfaces and check both axes after a theme change. `scrollFade` is an optional edge mask, not a loading signal. `overscrollContain` is useful in a fixed panel but can change how a user reaches the page beneath it. Content is not virtualized, so large lists still create all their HTML nodes.

The component attaches its factory on script load and `astro:page-load`. It
calls `destroy()` before an Astro page swap. For direct DOM changes, import
`createScrollArea` from the component index, attach the root, and destroy its
controller before removing the root.
