---
title: ScrollArea
description: Scroll native content with styled scrollbars, edge shadows, and
  optional virtualization.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# ScrollArea

> Scroll native content with styled scrollbars, edge shadows, and optional virtualization.

## Anatomy

```text
ScrollArea [component; slot=root]
├── viewport [slot]
│   └── content [slot]
├── scrollbar [slot]
│   └── thumb [slot]
└── corner [slot]
```

## Usage

Use ScrollArea to constrain overflowing content. Scrolling stays native: wheel, touch, keyboard,
and scroll anchoring behave as in any scroll container. ScrollArea hides the native scrollbar and
draws its own over the content. When the area is a landmark of its own, label it with
`role="region"` and `aria-label`.

```tsx
import { For } from 'solid-js'
import { ScrollArea } from 'moraine'

export function Example() {
  return (
    <ScrollArea class="h-48 w-full" role="region" aria-label="Recent activity">
      <For each={Array.from({ length: 12 }, (_, index) => index + 1)}>
        {(entry) => <p class="py-2 text-sm">Activity entry {entry}</p>}
      </For>
    </ScrollArea>
  )
}
```

### Structure and sizing

Set a height or maximum height on the root for vertical scrolling and a width for horizontal
scrolling. The root positions the scrollbars; the `viewport` scrolls; the `content` wraps the
children. Put content layout such as `flex` and `gap` on `classes.content`, not on the root.

`class`, `style`, `ref`, and other attributes such as `role` and `aria-label` go to the root.
`onScroll` and `tabIndex` go to the viewport, and `viewportRef` receives it. The viewport joins
the tab order while its content overflows and leaves it when the content fits; pass `tabIndex` to
override this.

### Orientation

`orientation` selects the scrollable axes: `vertical` (default), `horizontal`, or `both`. With
`both`, the two scrollbars meet at the `corner`. Horizontal and two-axis content grows to its
natural width.

```tsx
<ScrollArea orientation="horizontal" class="max-w-lg" classes={{ content: 'flex gap-3' }}>
  {milestones}
</ScrollArea>
```

### Scrollbars

`scrollbar` selects how scrollbars appear:

| Value    | Behavior                                                            |
| -------- | ------------------------------------------------------------------- |
| `auto`   | Custom scrollbars while an axis overflows. This is the default.     |
| `always` | Custom scrollbars at all times, even when content fits.             |
| `hover`  | Custom scrollbars while the pointer is over the area or it scrolls. |
| `scroll` | Custom scrollbars while the area scrolls.                           |
| `native` | Browser scrollbars.                                                 |
| `hidden` | No scrollbars; wheel, touch, and keyboard scrolling still work.     |

`hover` and `scroll` scrollbars stay visible for `scrollHideDelay` milliseconds (default `600`)
after activity ends. Drag the thumb to scroll, or press the track to jump to that position.
Scrollbars are hidden from assistive technology; keyboard scrolling goes through the focusable
viewport.

### Edge shadows

Set `shadow` to fade content out at edges that have more content beyond them. The shadow grows with
the remaining distance up to `shadowSize` pixels (default `40`), so it appears gradually instead of
switching on. The mask fades content into the background behind the container.

```tsx
<ScrollArea shadow shadowSize={24} class="h-48" role="region" aria-label="Activity">
  {entries}
</ScrollArea>
```

### Overflow state

`onOverflowChange` receives `{ x: { start, end }, y: { start, end } }` whenever the edges with
more content beyond them change. `start` and `end` are logical: in RTL content, the `x` start
edge is on the right. `scrollThreshold` sets how close to an edge, in pixels, scrolling counts as
reaching it.

`onTopReached`, `onBottomReached`, `onLeftReached`, and `onRightReached` fire once each time scrolling
reaches a physical edge (within `scrollThreshold`) of an overflowing axis; in RTL content
`onLeftReached` and `onRightReached` follow the physical edges, not the logical `start`/`end`. They
do not fire for the initial position. Combine `onBottomReached` with `scrollThreshold` to load more
content before the end.

`setController` receives a controller once, during setup. It holds the reactive `overflow` state and
`scrollToEdge(axis, edge, options)`. Store it and call `scrollToEdge` after mount: the viewport does
not exist during setup, so an earlier call does nothing.

```tsx
let controller: ScrollAreaT.Controller | undefined

;<ScrollArea
  scrollThreshold={48}
  onBottomReached={loadMore}
  setController={(value) => (controller = value)}
>
  {messages}
</ScrollArea>

controller?.scrollToEdge('y', 'end', { behavior: 'smooth' })
```

### Virtualization

Pass `items` and an `itemRender` component to render a collection; `itemRender` replaces `children`,
and `items` has no effect without it. `itemRender` is mounted as a component, so read `props.item`
and `props.index` lazily instead of destructuring them. Add a `virtualizer` from
`createListVirtualizer()` to render only the visible items; the viewport is its scroll container.
Spread `props.rowProps` on each row so the virtualizer can position and measure it. Create the
virtualizer with `horizontal` for `orientation="horizontal"`.

```tsx
import { createListVirtualizer } from 'moraine/virtualizer'

const virtualizer = createListVirtualizer<string>({ estimateSize: () => 32 })

<ScrollArea
  class="h-80"
  items={lines}
  virtualizer={virtualizer}
  itemRender={(props) => <div {...props.rowProps}>{props.item}</div>}
/>
```

### Data attributes and CSS variables

The root carries `data-orientation`, `data-overflow-x` and `data-overflow-y` while an axis
overflows, `data-overflow-{x,y}-{start,end}` for each overflowing edge, `data-scrolling`, and
`data-hovering`. Each scrollbar carries `data-orientation`, `data-visible`, `data-dragging`, and
`data-corner` while the corner is shown; the corner carries `data-visible`.

The root also exposes the remaining scroll distance of each edge in pixels as
`--scroll-area-overflow-x-start`, `--scroll-area-overflow-x-end`,
`--scroll-area-overflow-y-start`, and `--scroll-area-overflow-y-end`. Use them for custom
edge effects.

### Theme and instance overrides

Set `scrollArea.defaultVariants` to choose the scrollbar mode or enable shadows across a provider;
`scrollbar: 'native'` restores browser scrollbars everywhere. The recipe exposes
`--scroll-area-shadow-size` and the mask layers `--scroll-area-shadow-y` and
`--scroll-area-shadow-x`.

The shadow size resolves in this order, highest first: root `style`, `styles.root`, an explicit
`shadowSize`, then recipe and Theme defaults.

## Examples

### Shadow overflowing activity

Enable `shadow` on a vertical activity feed so clipped updates are visible at the edge.

```tsx
import { ScrollArea } from 'moraine'
import { For } from 'solid-js'

const entries = [
  'Reviewed the project brief.',
  'Agreed on the navigation structure.',
  'Added the first component examples.',
  'Checked keyboard interactions.',
  'Updated the shared theme tokens.',
  'Tested layouts on smaller screens.',
  'Published the accessibility notes.',
  'Prepared the next release.',
]

export function Shadow() {
  return (
    <ScrollArea
      shadow
      class="h-48"
      classes={{ content: 'pe-3 space-y-1' }}
      role="region"
      aria-label="Project activity"
    >
      <For each={entries}>
        {(entry, index) => (
          <div class="py-1.5 flex gap-2 items-baseline">
            <span class="text-xs text-muted-foreground shrink-0">Update {index() + 1}</span>
            <p class="text-sm">{entry}</p>
          </div>
        )}
      </For>
    </ScrollArea>
  )
}
```

### Scroll project milestones

Set `orientation="horizontal"` for a timeline. `dir="rtl"` scrolls from the right edge, and the
shadows follow the logical edges.

```tsx
import { ScrollArea } from 'moraine'
import { For } from 'solid-js'

const milestones = ['Planning', 'Design', 'Prototype', 'Implementation', 'Review', 'Release']

export function Horizontal() {
  return (
    <div class="w-full space-y-6">
      <For each={['ltr', 'rtl'] as const}>
        {(direction) => (
          <div class="space-y-3">
            <p class="text-sm font-medium">
              {direction === 'ltr' ? 'Left to right' : 'Right to left'}
            </p>
            <ScrollArea
              orientation="horizontal"
              shadow
              dir={direction}
              class="max-w-lg w-full"
              classes={{ content: 'pb-3 flex gap-3' }}
              role="region"
              aria-label={`${direction.toUpperCase()} project milestones`}
            >
              <For each={milestones}>
                {(milestone, index) => (
                  <div class="py-1.5 ps-3 border-s border-border shrink-0 w-32">
                    <p class="text-xs text-muted-foreground">Step {index() + 1}</p>
                    <p class="text-sm font-medium mt-1">{milestone}</p>
                  </div>
                )}
              </For>
            </ScrollArea>
          </div>
        )}
      </For>
    </div>
  )
}
```

### Scroll a wide table

Set `orientation="both"` for content that overflows in both directions.

```tsx
import { ScrollArea } from 'moraine'
import { For } from 'solid-js'

const columns = Array.from({ length: 12 }, (_, index) => `Week ${index + 1}`)
const rows = ['Design', 'Engineering', 'Marketing', 'Support', 'Sales', 'Finance', 'Legal']

export function BothAxes() {
  return (
    <ScrollArea
      orientation="both"
      class="border border-border rounded-md h-56 max-w-lg w-full"
      role="region"
      aria-label="Team capacity"
    >
      <table class="text-sm">
        <thead>
          <tr>
            <th class="font-medium px-3 py-2 text-start">Team</th>
            <For each={columns}>
              {(column) => (
                <th class="font-medium px-3 py-2 text-start whitespace-nowrap">{column}</th>
              )}
            </For>
          </tr>
        </thead>
        <tbody>
          <For each={rows}>
            {(row, rowIndex) => (
              <tr class="border-t border-border">
                <td class="font-medium px-3 py-2">{row}</td>
                <For each={columns}>
                  {(_column, columnIndex) => (
                    <td class="text-muted-foreground px-3 py-2 tabular-nums">
                      {((rowIndex() * 7 + columnIndex() * 13) % 60) + 40}%
                    </td>
                  )}
                </For>
              </tr>
            )}
          </For>
        </tbody>
      </table>
    </ScrollArea>
  )
}
```

### Jump to the latest notification

Read `onOverflowChange` to show whether more notifications are hidden, and call
`scrollToEdge` from the controller.

```tsx
import { Button, ScrollArea } from 'moraine'
import type { ScrollAreaT } from 'moraine'
import { For, Show, createSignal } from 'solid-js'

export function Overflow() {
  const [overflow, setOverflow] = createSignal<ScrollAreaT.Overflow>()
  let controller: ScrollAreaT.Controller | undefined

  return (
    <div class="max-w-sm w-full space-y-3">
      <ScrollArea
        shadow
        shadowSize={24}
        scrollThreshold={8}
        onOverflowChange={setOverflow}
        setController={(value) => (controller = value)}
        class="h-48 w-full"
        classes={{ content: 'pe-3 space-y-1' }}
        role="region"
        aria-label="Notifications"
      >
        <For each={Array.from({ length: 10 }, (_, index) => index + 1)}>
          {(entry) => <p class="text-sm py-1.5">Notification {entry}</p>}
        </For>
      </ScrollArea>
      <div class="flex gap-2 items-center justify-between">
        <p class="text-sm text-muted-foreground">
          More above: <output>{overflow()?.y.start ? 'yes' : 'no'}</output>, more below:{' '}
          <output>{overflow()?.y.end ? 'yes' : 'no'}</output>
        </p>
        <Show
          when={overflow()?.y.end}
          fallback={
            <Button
              size="sm"
              variant="outline"
              onClick={() => controller?.scrollToEdge('y', 'start', { behavior: 'smooth' })}
            >
              Back to top
            </Button>
          }
        >
          <Button
            size="sm"
            variant="outline"
            onClick={() => controller?.scrollToEdge('y', 'end', { behavior: 'smooth' })}
          >
            Jump to latest
          </Button>
        </Show>
      </div>
    </div>
  )
}
```

### Load more at the end

`onBottomReached` with `scrollThreshold` requests the next page shortly before the end.

```tsx
import { ScrollArea } from 'moraine'
import { For, Show, createSignal } from 'solid-js'

const PAGE_SIZE = 15
const TOTAL = 75

export function Infinite() {
  const [count, setCount] = createSignal(PAGE_SIZE)
  const [loading, setLoading] = createSignal(false)

  function loadMore(): void {
    if (loading() || count() >= TOTAL) {
      return
    }
    setLoading(true)
    setTimeout(() => {
      setCount((current) => Math.min(current + PAGE_SIZE, TOTAL))
      setLoading(false)
    }, 600)
  }

  return (
    <ScrollArea
      scrollThreshold={48}
      onBottomReached={loadMore}
      class="h-64 max-w-sm w-full"
      classes={{ content: 'pe-3' }}
      role="region"
      aria-label="Order history"
    >
      <For each={Array.from({ length: count() }, (_, index) => index + 1)}>
        {(order) => (
          <div class="text-sm py-2 border-b border-border flex justify-between">
            <span>Order #{1000 + order}</span>
            <span class="text-muted-foreground">${(order * 17) % 300}.00</span>
          </div>
        )}
      </For>
      <p class="text-xs text-muted-foreground py-3 text-center" aria-live="polite">
        <Show when={count() < TOTAL} fallback="All orders loaded">
          {loading() ? 'Loading more orders…' : 'Scroll for more'}
        </Show>
      </p>
    </ScrollArea>
  )
}
```

### Virtualize a long log

`items`, `itemRender`, and `virtualizer` render 10,000 lines while mounting only the visible ones.

```tsx
import { ScrollArea } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const LOG_LINES = Array.from({ length: 10_000 }, (_, index) => `Request ${index + 1} completed`)

export function Virtualized() {
  const virtualizer = createListVirtualizer<string>({ estimateSize: () => 32, overscan: 8 })

  return (
    <ScrollArea
      shadow
      items={LOG_LINES}
      virtualizer={virtualizer}
      itemRender={(props) => (
        <div {...props.rowProps} class="text-sm px-3 py-1.5 flex gap-3 tabular-nums">
          <span class="text-muted-foreground w-12">{props.index + 1}</span>
          <span>{props.item}</span>
        </div>
      )}
      class="border border-border rounded-md h-80 max-w-md w-full"
      role="region"
      aria-label="Request log"
    />
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-hovering` | `scroll-area` | — |
| `data-orientation` | `scroll-area`, `scroll-area-scrollbar` | Stores the rendered orientation (horizontal or vertical). |
| `data-overflow-x` | `scroll-area` | — |
| `data-overflow-x-end` | `scroll-area` | — |
| `data-overflow-x-start` | `scroll-area` | — |
| `data-overflow-y` | `scroll-area` | — |
| `data-overflow-y-end` | `scroll-area` | — |
| `data-overflow-y-start` | `scroll-area` | — |
| `data-scrolling` | `scroll-area` | — |
| `data-corner` | `scroll-area-scrollbar` | — |
| `data-dragging` | `scroll-area-scrollbar` | Present while the related thumb or handle is being dragged. |
| `data-visible` | `scroll-area-scrollbar`, `scroll-area-corner` | — |

### Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| itemRender | Component<ItemRenderProps<TItem>> \| undefined | — | Renders one collection item. Takes the place of `children`. It is mounted as a component, so<br>read `props.item` and `props.index` lazily instead of destructuring them. |
| items | readonly TItem[] \| undefined | — | Reactive collection rendered with `itemRender`. Has no effect without `itemRender`. |
| onBottomReached | (() => void) \| undefined | — | Called once each time scrolling reaches the bottom edge (within `scrollThreshold`) of an overflowing vertical axis, such as to load more items. |
| onLeftReached | (() => void) \| undefined | — | Called once each time scrolling reaches the left edge (within `scrollThreshold`) of an overflowing horizontal axis; in RTL content that is the logical end. |
| onOverflowChange | ((overflow: Overflow) => void) \| undefined | — | Called with the new `Overflow` whenever content starts or stops extending beyond an edge, for example while scrolling or after a resize. |
| onRightReached | (() => void) \| undefined | — | Called once each time scrolling reaches the right edge (within `scrollThreshold`) of an overflowing horizontal axis; in RTL content that is the logical start. |
| onTopReached | (() => void) \| undefined | — | Called once each time scrolling returns to the top edge (within `scrollThreshold`) of an overflowing vertical axis; not called for the initial position. |
| orientation | 'vertical' \| 'horizontal' \| 'both' \| undefined | 'vertical' | Scrollable axes. |
| scrollbar | 'auto' \| 'always' \| 'hover' \| 'scroll' \| 'native' \| 'hidden' \| undefined | 'auto' | Scrollbar presentation. `auto` shows custom scrollbars while an axis overflows, `always` keeps<br>them visible, `hover` shows them while the pointer is over the area or it scrolls, `scroll`<br>shows them while it scrolls, `native` keeps browser scrollbars, and `hidden` hides every<br>scrollbar while retaining scrolling. |
| scrollHideDelay | number \| undefined | 600 | Milliseconds `hover` and `scroll` scrollbars stay visible after pointer or scroll activity ends. Other scrollbar modes ignore it. |
| scrollThreshold | number \| undefined | 0 | Distance in pixels from an edge within which it counts as reached. It also decides when the edge shadows and the `on*Reached` callbacks respond. Negative values count as `0`. |
| setController | ((controller: Controller) => void) \| undefined | — | Receives the imperative controller once, during setup. Store it and call it later; the viewport<br>only exists after mount, so `scrollToEdge` called during setup does nothing. |
| shadow | boolean \| undefined | false | Whether edges with more content beyond them fade out as a shadow. |
| shadowSize | number \| undefined | 40 | Length in pixels of the edge fade shadows while the `shadow` variant is enabled. Negative values count as `0`. |
| viewportRef | Ref<HTMLDivElement> \| undefined | — | Receives the native scrolling `<div>` that wraps the content, to read or set `scrollTop` and similar. |
| virtualizer | Virtualizer<TItem> \| undefined | — | Renders only the visible `items`. The viewport is the scroll container; create the<br>virtualizer with `horizontal` for `orientation="horizontal"`. Requires `itemRender`, and<br>the row element must spread `props.props` so the virtualizer can position and measure it. |
| children | JSX.Element \| undefined | — | Content rendered inside the viewport. Ignored when `itemRender` is set. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`itemRender` example**

```tsx
import { ScrollArea } from 'moraine'

<ScrollArea
  class="h-48"
  items={['Alpha', 'Beta', 'Gamma']}
  itemRender={(props) => (
    <p>
      {props.index + 1}. {props.item}
    </p>
  )}
/>
```

**`setController` example**

```tsx
import { ScrollArea } from 'moraine'
import type { ScrollAreaT } from 'moraine'

let controller: ScrollAreaT.Controller | undefined

<>
  <button onClick={() => controller?.scrollToEdge('y', 'end', { behavior: 'smooth' })}>
    Jump to bottom
  </button>
  <ScrollArea class="h-48" setController={(value) => (controller = value)}>
    Long content
  </ScrollArea>
</>
```

**`virtualizer` example**

```tsx
import { ScrollArea } from 'moraine'
import { createListVirtualizer } from 'moraine/virtualizer'

const rows = Array.from({ length: 10000 }, (_, index) => `Row ${index + 1}`)
const virtualizer = createListVirtualizer<string>({ estimateSize: () => 32 })

<ScrollArea
  class="h-64"
  items={rows}
  virtualizer={virtualizer}
  itemRender={(props) => <div {...props.props}>{props.item}</div>}
/>
```
