Scroll Area
updatedScrollbars that don't look like Windows 98. Custom bars over a native scroller, with optional virtualization.
Installation
Usage
<script setup lang="ts">
import { ScrollArea } from '@/components/ui/scroll-area'
</script>
<template>
<ScrollArea class="h-72 rounded-lg border">
<div class="p-4">…</div>
</ScrollArea>
</template>
ScrollArea sizes from its content and scrolls once you bound it: h-*, max-h-*, flex-1 in a column, a grid row, h-full. Without a bound it shows everything, like a div.
The scrolling stays native. Only the scrollbar is custom. On touch screens, the bars only show where you are, and touches go straight to the content.
Examples
Inside a Card
With max-h-48, the body grows with its content and starts scrolling at 192px, while the header and footer stay in view.
Activity
The latest builds on main.
Always visible
visible forces the bars on or off. delay sets how long they stay after scrolling stops. While they're shown, the root has data-active.
Offsets
Styling
The bar is its own component, ScrollBar, with its own class. The thumb's look lives in your copy of ScrollBar.vue, so edit it there. You can also reach any part from the root's class through data-slot and data-axis:
Horizontal
orientation is vertical by default, horizontal, or both. A vertical area won't scroll sideways, so content that overflows horizontally needs horizontal or both. Right-to-left is mirrored either way.
A vertical area gives its content the area's width, so truncate, line-clamp-* and percentage widths work inside it as they do anywhere else. With horizontal or both, the content grows to its longest line instead, and a part that must stay narrower needs a width of its own.
Both axes
orientation="both" draws two bars that meet in the corner. To keep the corner free, use verticalOffset and horizontalOffset. With virtualize, only the rows are virtualized, unless you add columns.
Edge fade
While the area can still scroll towards an edge, the root has data-overflow-x-start, -x-end, -y-start or -y-end. Pair it with scroll-fade-overlay-x for gradients, or show controls with group-has-[[data-overflow-x-end]]. No scroll listeners needed.
The buttons in the demo scroll by 80% of the width with setScrollPosition.
Edge events
reachEdge fires once when you scroll into an edge zone, with { edge, ref }, and again only after you leave it. edgeOffset widens the zone in pixels. Want to load more on reach? That's Infinite Scroll, which ships with this component.
Scroll to an edge.
Virtualize
10,000 rows, 20 in the DOM. Set virtualize and pass items, and the default slot renders only what's on screen (plus a small buffer), with { item, index }.
virtualize needs a bound: h-*, max-h-*, or a flex or grid parent that sizes the area. The list scrolls inside the area, so without one the area grows to the whole list and renders every item; in development it warns once.
estimateSize is just a guess: real sizes are measured after render, so items can have different heights. It runs on TanStack Virtual, which is why it installs @tanstack/vue-virtual.
Horizontal virtualize
A horizontal list needs a height: its items are positioned across the strip, so they can't give it one.
Masonry
Pinterest at home. lanes and gap turn the list into a masonry grid.
Grid
A spreadsheet's worth of cells. With orientation="both", columns in virtualize virtualizes the columns as well as the rows, and the default slot renders once per visible cell with { item, index, column }. item and index are the row's; column is { index, start, size }.
Column widths start from columns.estimateSize, a number or a function of the index. A cell is never narrower than its column, and one with wider content widens the whole column. scrollToColumn(index, edge?) scrolls sideways the way scrollTo scrolls down.
Without columns, rows wider than the area still scroll sideways, but nothing measures their width, so there's no horizontal bar and no data-overflow-x-*.
Programmatic scroll
scrollTo(index, edge?) scrolls to an item. Pass 'start', 'center' or 'end' to align it; leave edge out, and an already visible item stays where it is.
@virtual-scroll fires with { index, from, to, direction, ref } whenever the item at the scroll position changes.
Without items, setScrollPosition(axis, offset, duration?) and setScrollPercentage(axis, fraction, duration?) scroll by pixels or by a fraction of the way. Both measure the content when called, so after you append a message and await nextTick(), setScrollPercentage('vertical', 1) lands on the new end.
setScrollPositionSilently(axis, offset) jumps at once and emits nothing for that move: no scroll, reachEdge or virtualScroll, and the bar doesn't flash. Use it to put back a saved position without your handlers taking it for the user's scroll; it works right in onMounted, before a virtual list has attached to the viewport. Native scroll listeners still see the move, InfiniteScroll included.
Keys and anchoring
A chat loads older messages above the one you're reading. Rows are keyed by index, so a row added at the top shifts every row below it into its neighbour's element. Give virtualize a getItemKey, and each row keeps its element, its state and its measured size wherever it moves.
anchorTo: 'end' keeps the first visible row where it is when rows are added or removed at either end, and keeps a view that is at the end there while the last row grows, as a streamed reply does. Holding a row in place needs getItemKey. followOnAppend (true, or 'smooth' to animate) makes a view at the end follow rows appended below it.
Loading the older rows with InfiniteScroll? Pass the area's API as its target, so it leaves the position to the anchor instead of shifting it a second time.
External scroll element
Want to virtualize against a parent scroller, like the page itself? Pass getScrollElement and scrollMargin (the list's offset from the top of that scroller) to virtualize. The component then grows to the list's full size and draws no bars.
getScrollElement must return the element right at mount. If it returns null first and the element later, the list won't attach to anything.
Data you don't hold
Pass items-size and items-fn instead of items. The function is called with (from, size), only for what's on screen.
API Reference
ScrollArea
class is also accepted, for the root.
The scroll payload carries the same object as ref, so one handler can serve many areas without template refs. The exposed virtualizer is outside this component's API stability: if the engine changes, code built on it changes with it.
| Prop | Default | Type and description |
|---|---|---|
| visible | null | boolean | nullForces the bar on ( |
| scrollbar | true | booleanRenders the bar and its thumb. With |
| delay | 1000 | string | numberMilliseconds the bar lingers after the content or position last changed. |
| tabindex | — | string | numberLands on the viewport, the element that scrolls and receives focus. |
| orientation | "vertical" | ScrollAreaOrientationThe axis the area scrolls on, |
| verticalOffset | [0, 0] | [number, number]Space in pixels kept free at the start and end of the vertical bar's track. |
| horizontalOffset | [0, 0] | [number, number]Space in pixels kept free at the start and end of the horizontal bar's track. |
| edgeOffset | 0 | numberDistance in pixels from an edge at which |
| virtualize | false | boolean | ScrollAreaVirtualizeOptionsRender only the items in and near the view. Needs a bound on the scrolling axis ( |
| virtualize.estimateSize | — | number | ((index: number) => number)Estimated size of an item in pixels, or a function of its index. Real sizes are measured after render. 24 by default. |
| virtualize.overscan | — | numberExtra items rendered on each side of the view. 4 by default. |
| virtualize.lanes | — | numberNumber of lanes, for a masonry layout. 1 by default. Ignored with |
| virtualize.gap | — | numberSpace between items and between lanes, in pixels. 0 by default. |
| virtualize.scrollMargin | — | numberThe list's offset from the start of an external scroll element. |
| virtualize.getScrollElement | — | (() => HTMLElement | null)Returns an ancestor to scroll instead of the component's own viewport. Must return the element at mount. |
| virtualize.columns | — | ScrollAreaVirtualizeColumnsVirtualizes columns as well as rows, with |
| virtualize.getItemKey | — | ((index: number) => ScrollAreaItemKey)Returns the key of the item at an index. Rows are keyed by it instead of their index, so a row keeps its element and measured size when rows arrive above it. |
| virtualize.anchorTo | — | "start" | "end"
|
| virtualize.followOnAppend | — | boolean | ScrollBehaviorWith |
| items | [] | readonly T[]The list to virtualize. The default slot renders once per item in the rendered window. |
| itemsSize | — | numberTotal item count, for use with |
| itemsFn | — | ((from: number, size: number) => T[])Called with |
| Event | Payload and description |
|---|---|
| scroll | [info: ScrollAreaScrollInfo & { ref: ScrollAreaApi; }]Fires on scroll with positions, percentages and sizes for both axes, and |
| virtualScroll | [info: ScrollAreaVirtualInfo & { ref: ScrollAreaApi; }]Fires when the item at the scroll position changes, with |
| reachEdge | [info: { edge: ScrollAreaEdge; ref: ScrollAreaApi; }]Fires once when the position enters an edge zone, with |
| Slot | Scope and description |
|---|---|
| default | { item: T; index: number; column?: ScrollAreaVirtualColumn | undefined; }The content. When virtualized, rendered once per item with |
| Member | Type and description |
|---|---|
| getScrollTarget | () => HTMLElement | nullReturns the element that scrolls. |
| getScroll | () => ScrollAreaScrollInfoReturns the same information as the |
| getScrollPosition | () => { top: number; left: number; }Returns |
| getScrollPercentage | () => { top: number; left: number; }Returns |
| setScrollPosition | (axis: ScrollAreaAxis, offset: number, duration?: number | undefined) => voidScrolls an axis to an offset in pixels, animated over |
| setScrollPositionSilently | (axis: ScrollAreaAxis, offset: number) => voidSets an axis to an offset in pixels at once, without emitting |
| setScrollPercentage | (axis: ScrollAreaAxis, percentage: number, duration?: number | undefined) => voidScrolls an axis to a fraction from 0 to 1, animated over |
| scrollTo | (index: number, edge?: ScrollAreaVirtualEdge | undefined) => voidScrolls a virtualized list to an item. |
| scrollToColumn | (index: number, edge?: ScrollAreaVirtualEdge | undefined) => voidScrolls a virtual grid to a column, with the same |
| reset | () => voidDrops every measured item size, and every column width in a grid, and measures again. |
| refresh | (index?: number | undefined) => voidRe-measures from an index onward, or everything, column widths included; the scroll position is kept. |
| virtualizer | Virtualizer<HTMLElement, Element>The raw TanStack Virtual instance. An escape hatch outside this component's API stability. |
| columnVirtualizer | Virtualizer<HTMLElement, Element> | undefinedThe raw TanStack Virtual instance of a grid's columns, |
ScrollBar
class is also accepted and merged over the bar's base classes. The thumb's classes are not exposed; edit your copy to change them.
| Prop | Default | Type and description |
|---|---|---|
| axis* | — | ScrollAreaAxisWhich bar this is. |
InfiniteScroll
class is also accepted, for the root.
| Prop | Default | Type and description |
|---|---|---|
| onLoad* | — | InfiniteScrollLoadCalled with |
| target | null | InfiniteScrollTarget | nullWhat scrolls. An element, the |
| directions | ["bottom"] | InfiniteDirection[]The edges to load from. |
| offset | 200 | numberDistance in pixels from an edge at which a load starts. 200 by default. |
| debounce | 100 | numberMilliseconds between checks while scrolling. 100 by default; 0 checks on every scroll event. |
| initialFill | true | booleanAfter each load, load again while the content does not fill the viewport. On by default. |
| disabled | false | booleanStops loading. Turning it off checks the edges at once. |
| resetKey | — | unknownAny value; when it changes, every direction resets to index 0 and starts over. |
| shouldLoad | — | ((direction: InfiniteDirection) => boolean | undefined)Your own "time to load?" check for an edge, called with its direction in place of the |
| Slot | Scope and description |
|---|---|
| default | anyThe content. |
| loading | { direction: InfiniteDirection; }What shows at an edge while it loads; a |
| end | { direction: InfiniteDirection; }What shows at an edge once it is stopped. Receives |
| Member | Type and description |
|---|---|
| state | Readonly<Ref<Record<InfiniteDirection, InfiniteScrollState>, Record<InfiniteDirection, InfiniteScrollState>>>The |
| trigger | (direction?: InfiniteDirection | undefined) => voidLoads a direction now, unless it is loading, stopped or disabled. The first listed direction by default. |
| stop | (direction?: InfiniteDirection | undefined) => voidStops a direction, or all of them. |
| resume | (direction?: InfiniteDirection | undefined) => voidStarts a stopped direction again, or all of them, and checks the edges. |
| reset | (direction?: InfiniteDirection | undefined) => voidSets a direction, or all of them, back to index 0 and not stopped, then checks the edges. |
| setIndex | (direction: InfiniteDirection, index: number) => voidSets the next load index of a direction. |
| poll | () => voidChecks the edges now, after content changed without a scroll. |
| getTarget | () => ScrollTarget | nullThe resolved scroll target. |
class is also accepted, for the root.
The scroll payload carries the same object as ref, so one handler can serve many areas without template refs. The exposed virtualizer is outside this component's API stability: if the engine changes, code built on it changes with it.
Props
- visible
null boolean | nullForces the bar on (true) or off (false).nullshows it on hover and while scrolling.- scrollbar
true booleanRenders the bar and its thumb. Withfalsethe area still scrolls by wheel, touch and keyboard.- delay
1000 string | numberMilliseconds the bar lingers after the content or position last changed.- tabindex
string | numberLands on the viewport, the element that scrolls and receives focus.- orientation
"vertical" ScrollAreaOrientationThe axis the area scrolls on,vertical,horizontalorboth. Sets the viewport's overflow, the virtualized axis (bothvirtualizes the vertical one, and the columns too withvirtualize.columns) and which bars render.- verticalOffset
[0, 0] [number, number]Space in pixels kept free at the start and end of the vertical bar's track.- horizontalOffset
[0, 0] [number, number]Space in pixels kept free at the start and end of the horizontal bar's track.- edgeOffset
0 numberDistance in pixels from an edge at whichreachEdgecounts the edge as reached. 0 by default.- virtualize
false boolean | ScrollAreaVirtualizeOptionsRender only the items in and near the view. Needs a bound on the scrolling axis (h-*,max-h-*, a flex or grid parent), and a height when horizontal.trueuses the defaults; an object sets them. Withcolumnsandorientation="both"it virtualizes a grid.- virtualize.estimateSize
number | ((index: number) => number)Estimated size of an item in pixels, or a function of its index. Real sizes are measured after render. 24 by default.- virtualize.overscan
numberExtra items rendered on each side of the view. 4 by default.- virtualize.lanes
numberNumber of lanes, for a masonry layout. 1 by default. Ignored withcolumns.- virtualize.gap
numberSpace between items and between lanes, in pixels. 0 by default.- virtualize.scrollMargin
numberThe list's offset from the start of an external scroll element.- virtualize.getScrollElement
(() => HTMLElement | null)Returns an ancestor to scroll instead of the component's own viewport. Must return the element at mount.- virtualize.columns
ScrollAreaVirtualizeColumnsVirtualizes columns as well as rows, withorientation="both"only:{ count, estimateSize?, overscan?, gap? }.estimateSizeis a column's width in pixels or a function of its index, 120 by default, and widens to the widest rendered cell;overscanis 2 andgap0 by default.- virtualize.getItemKey
((index: number) => ScrollAreaItemKey)Returns the key of the item at an index. Rows are keyed by it instead of their index, so a row keeps its element and measured size when rows arrive above it.- virtualize.anchorTo
"start" | "end"start(default) orend. Withend, the first visible row stays in place, by key, when rows are added or removed at either end, and a view at the end stays there while the last row grows.- virtualize.followOnAppend
boolean | ScrollBehaviorWithanchorTo: 'end', a view at the end follows rows appended below it:truejumps,'smooth'animates. Off by default.- items
[] readonly T[]The list to virtualize. The default slot renders once per item in the rendered window.- itemsSize
numberTotal item count, for use withitemsFninstead ofitems.- itemsFn
((from: number, size: number) => T[])Called with(from, size)for the rendered window only, for data you do not want to hold in memory.
Emits
- scroll
[info: ScrollAreaScrollInfo & { ref: ScrollAreaApi; }]Fires on scroll with positions, percentages and sizes for both axes, andref, the exposed API.- virtualScroll
[info: ScrollAreaVirtualInfo & { ref: ScrollAreaApi; }]Fires when the item at the scroll position changes, with{ index, from, to, direction, ref }.- reachEdge
[info: { edge: ScrollAreaEdge; ref: ScrollAreaApi; }]Fires once when the position enters an edge zone, with{ edge, ref }.edgeistop,bottom,startorend;startandendare logical. It fires again only after the position leaves the zone, and never at mount.
Slots
- default
{ item: T; index: number; column?: ScrollAreaVirtualColumn | undefined; }The content. When virtualized, rendered once per item with{ item, index }; in a grid, once per visible cell with{ item, index, column }, wherecolumnis{ index, start, size }.
Exposed
- getScrollTarget
() => HTMLElement | nullReturns the element that scrolls.- getScroll
() => ScrollAreaScrollInfoReturns the same information as thescrollevent.- getScrollPosition
() => { top: number; left: number; }Returns{ top, left }in pixels.leftcounts from the right edge underdir="rtl".- getScrollPercentage
() => { top: number; left: number; }Returns{ top, left }as fractions from 0 to 1.- setScrollPosition
(axis: ScrollAreaAxis, offset: number, duration?: number | undefined) => voidScrolls an axis to an offset in pixels, animated overdurationmilliseconds when given.- setScrollPositionSilently
(axis: ScrollAreaAxis, offset: number) => voidSets an axis to an offset in pixels at once, without emittingscroll,reachEdgeorvirtualScrollfor that move or showing the bar. Native scroll listeners still see it.- setScrollPercentage
(axis: ScrollAreaAxis, percentage: number, duration?: number | undefined) => voidScrolls an axis to a fraction from 0 to 1, animated overdurationmilliseconds when given.- scrollTo
(index: number, edge?: ScrollAreaVirtualEdge | undefined) => voidScrolls a virtualized list to an item.edgeisstart,centerorend; omit it to leave a visible item where it is.- scrollToColumn
(index: number, edge?: ScrollAreaVirtualEdge | undefined) => voidScrolls a virtual grid to a column, with the sameedgeasscrollTo. Does nothing withoutvirtualize.columns.- reset
() => voidDrops every measured item size, and every column width in a grid, and measures again.- refresh
(index?: number | undefined) => voidRe-measures from an index onward, or everything, column widths included; the scroll position is kept.- virtualizer
Virtualizer<HTMLElement, Element>The raw TanStack Virtual instance. An escape hatch outside this component's API stability.- columnVirtualizer
Virtualizer<HTMLElement, Element> | undefinedThe raw TanStack Virtual instance of a grid's columns,undefinedwithoutvirtualize.columns. Outside this component's API stability, likevirtualizer.
class is also accepted and merged over the bar's base classes. The thumb's classes are not exposed; edit your copy to change them.
Props
- axis*
ScrollAreaAxisWhich bar this is.ScrollArearenders one for itsorientation.
class is also accepted, for the root.
Props
- onLoad*
InfiniteScrollLoadCalled with{ direction, index }when an edge is near.indexcounts loads in that direction from 1. Resolve to load again later, resolve'stop'when that direction has no more; a rejection rolls the index back and reports the error.- target
null InfiniteScrollTarget | nullWhat scrolls. An element, thewindow, or aScrollAreaAPI. Left out, the surroundingScrollArea's viewport, else the nearest scrolling ancestor, else the window.- directions
["bottom"] InfiniteDirection[]The edges to load from.top,bottom,startandend;startandendare logical.['bottom']by default.- offset
200 numberDistance in pixels from an edge at which a load starts. 200 by default.- debounce
100 numberMilliseconds between checks while scrolling. 100 by default; 0 checks on every scroll event.- initialFill
true booleanAfter each load, load again while the content does not fill the viewport. On by default.- disabled
false booleanStops loading. Turning it off checks the edges at once.- resetKey
unknownAny value; when it changes, every direction resets to index 0 and starts over.- shouldLoad
((direction: InfiniteDirection) => boolean | undefined)Your own "time to load?" check for an edge, called with its direction in place of theoffsetcheck. Returnundefinedto fall back tooffset.
Slots
- default
anyThe content.- loading
{ direction: InfiniteDirection; }What shows at an edge while it loads; aSpinnerby default. Receives{ direction }.- end
{ direction: InfiniteDirection; }What shows at an edge once it is stopped. Receives{ direction }.
Exposed
- state
Readonly<Ref<Record<InfiniteDirection, InfiniteScrollState>, Record<InfiniteDirection, InfiniteScrollState>>>The{ index, loading, stopped }of each direction.- trigger
(direction?: InfiniteDirection | undefined) => voidLoads a direction now, unless it is loading, stopped or disabled. The first listed direction by default.- stop
(direction?: InfiniteDirection | undefined) => voidStops a direction, or all of them.- resume
(direction?: InfiniteDirection | undefined) => voidStarts a stopped direction again, or all of them, and checks the edges.- reset
(direction?: InfiniteDirection | undefined) => voidSets a direction, or all of them, back to index 0 and not stopped, then checks the edges.- setIndex
(direction: InfiniteDirection, index: number) => voidSets the next load index of a direction.- poll
() => voidChecks the edges now, after content changed without a scroll.- getTarget
() => ScrollTarget | nullThe resolved scroll target.
Data attributes
| data-slot | Attributes | Description |
|---|---|---|
| scroll-area | data-active, data-orientation, data-overflow-x-start, data-overflow-x-end, data-overflow-y-start, data-overflow-y-end | The root. Each data-overflow attribute is present while the viewport can still scroll towards that edge; x-start is the right edge in right-to-left. |
| scroll-area-viewport | — | The native scroller. Receives tabindex. |
| scroll-area-content | data-active | Wraps the slot. |
| scroll-area-virtual | — | The sized container for virtual items. |
| scroll-area-item | data-index | One virtual item, or one row of a grid. |
| scroll-area-cell | data-index | One cell of a virtual grid, inside its row. data-index is the column's index. |
| scroll-area-bar | data-axis | The track. Hidden from screen readers; lets touches through. |
| scroll-area-thumb | data-axis | The thumb, draggable with a mouse or pen. Hidden from screen readers; lets touches through. |
Accessibility
tabindex goes to the viewport, the element that actually scrolls. Other attributes, aria-label included, go to the root, so a label names the wrapper, not the focusable element.
Once focused, the viewport scrolls with the keyboard:
| Key | Action |
|---|---|
| ↑ ↓ ← → | Scrolls by a line on the active axis. |
| Page Up / Page Down | Scrolls by a page. |
| Home / End | Scrolls to the start or the end. |
| Space | Scrolls down by a page; Shift+Space scrolls up. |