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

Scroll Area for Astro

Native scrolling for Astro panels, with custom tracks, keyboard access, and optional edge fades.

  • Project file 1
  • Project file 2
  • Project file 3
  • Project file 4
  • Project file 5
  • Project file 6
  • Project file 7
  • Project file 8
  • Project file 9
  • Project file 10
  • Project file 11
  • Project file 12
  • Project file 13
  • Project file 14
  • Project file 15
  • Project file 16

Installation

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

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/scroll-area/index.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
---
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
---
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
import {
    clearRootBinding,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'

export interface ScrollAreaController {
    destroy(): void
}

export function createScrollArea(root: HTMLElement): ScrollAreaController {
    const existing = getRootBinding<ScrollAreaController>(
        root,
        '@gnostic/scroll-area',
    )
    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?.()
            clearRootBinding(root, '@gnostic/scroll-area', controller)
        },
    }
    return setRootBinding(root, '@gnostic/scroll-area', controller)
}

export function create(scope: ParentNode = document): ScrollAreaController[] {
    return getRoots<HTMLElement>(scope, 'scroll-area')
        .filter((root) => !hasRootBinding(root, '@gnostic/scroll-area'))
        .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
---
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
---
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
---
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
---
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
---
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
/** 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
}

Usage

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

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

Row 1: This longer line can scroll in both directions.

Row 2: This longer line can scroll in both directions.

Row 3: This longer line can scroll in both directions.

Row 4: This longer line can scroll in both directions.

Row 5: This longer line can scroll in both directions.

Row 6: This longer line can scroll in both directions.

Row 7: This longer line can scroll in both directions.

Row 8: This longer line can scroll in both directions.

Row 9: This longer line can scroll in both directions.

Row 10: This longer line can scroll in both directions.

Row 11: This longer line can scroll in both directions.

Row 12: This longer line can scroll in both directions.

Row 13: This longer line can scroll in both directions.

Row 14: This longer line can scroll in both directions.

Row 15: This longer line can scroll in both directions.

Row 16: This longer line can scroll in both directions.

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.

  • Activity 1: The project is ready for review.
  • Activity 2: The project is ready for review.
  • Activity 3: The project is ready for review.
  • Activity 4: The project is ready for review.
  • Activity 5: The project is ready for review.
  • Activity 6: The project is ready for review.
  • Activity 7: The project is ready for review.
  • Activity 8: The project is ready for review.
  • Activity 9: The project is ready for review.
  • Activity 10: The project is ready for review.
  • Activity 11: The project is ready for review.
  • Activity 12: The project is ready for review.
  • Activity 13: The project is ready for review.
  • Activity 14: The project is ready for review.
  • Activity 15: The project is ready for review.
  • Activity 16: The project is ready for review.

Horizontal scrolling

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

  1. Step 1Plan
  2. Step 2Design
  3. Step 3Build
  4. Step 4Review
  5. Step 5Release

Both scrollbars

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

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.

  • Notification 1: A new file is available.
  • Notification 2: A new file is available.
  • Notification 3: A new file is available.
  • Notification 4: A new file is available.
  • Notification 5: A new file is available.
  • Notification 6: A new file is available.
  • Notification 7: A new file is available.
  • Notification 8: A new file is available.
  • Notification 9: A new file is available.
  • Notification 10: A new file is available.
  • Notification 11: A new file is available.
  • Notification 12: A new file is available.

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.

Current project

The content fills the viewport.

Last updated today

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.

  • Update 1: Content is ready for review.
  • Update 2: Content is ready for review.
  • Update 3: Content is ready for review.
  • Update 4: Content is ready for review.
  • Update 5: Content is ready for review.
  • Update 6: Content is ready for review.
  • Update 7: Content is ready for review.
  • Update 8: Content is ready for review.
  • Update 9: Content is ready for review.
  • Update 10: Content is ready for review.
  • Update 11: Content is ready for review.
  • Update 12: Content is ready for review.

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.

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.

Tasks

  • Review task 1
  • Review task 2
  • Review task 3
  • Review task 4
  • Review task 5
  • Review task 6
  • Review task 7
  • Review task 8
  • Review task 9
  • Review task 10
  • Review task 11
  • Review task 12
  • Review task 13
  • Review task 14
  • Review task 15
  • Review task 16

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

PropType
orientation?'vertical' | 'horizontal' | 'both'

Allowed scroll directions.

Type'vertical' | 'horizontal' | 'both'
Default'vertical'
scrollFade?boolean

Fade edges that have more content.

Typeboolean
Defaultfalse
scrollbarGutter?boolean

Reserve space for the enabled scrollbars.

Typeboolean
Defaultfalse
fill?boolean

Size the content wrapper to fill the viewport.

Typeboolean
Defaultfalse
clampContentMinWidth?boolean

Allow the content wrapper to shrink to the viewport width.

Typeboolean
Defaulttrue
overscrollContain?boolean

Contain scroll input on overflowing axes.

Typeboolean
Defaultfalse

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