Menu

Components

Scroll Area

An area that scrolls, with scrollbars that match the theme and stay out of the way.

Introduction

The scrollbars of a browser and of an operating system are all different, and are often wide, grey and always there. Scroll Area draws its own, in the colors of your theme, over the content, and shows them when they are needed.

  • The browser still does the scrolling, so the wheel, the trackpad, touch and the keyboard work as they always do, and so does scroll momentum.
  • The scrollbars lie over the content and take no room, so nothing moves when they appear.
  • A thumb can be dragged, and a press in the lane goes to that place.
  • Vertical, horizontal, or both, three sizes, and an option to fade the edge that has more behind it.
  • When there is more to scroll to, the area is reached with Tab and scrolled with the arrow keys, and a screen reader is told its name.

Give the area a size with className: a height for a vertical one, a width for a horizontal one, both for one that scrolls both ways, or a max-h-* so that it grows until it reaches that. It is a Client Component, and what is inside it can be rendered on the server.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/scroll-area-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for ScrollArea. The browser scrolls the content (so touch, the wheel and
// the keyboard all work as they always do) and its own scrollbars are hidden;
// the ones drawn here lie over the content and take no room.
export const scrollAreaStyles = tv({
  slots: {
    root: "relative overflow-hidden",
    viewport: [
      "size-full max-h-[inherit] max-w-[inherit] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
      "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
    ],
    content: "",
    // The lane a thumb moves in. It is see-through; only the thumb is drawn.
    scrollbar:
      "absolute z-10 flex touch-none p-0.5 opacity-0 transition-opacity duration-150 select-none data-[visible=true]:opacity-100 data-[visible=false]:pointer-events-none",
    thumb:
      "relative rounded-full bg-fg/25 transition-colors hover:bg-fg/40 data-[dragging=true]:bg-fg/50",
  },
  variants: {
    orientation: {
      vertical: {
        viewport: "overflow-x-hidden overflow-y-auto",
        content: "",
      },
      horizontal: {
        viewport: "overflow-x-auto overflow-y-hidden",
        content: "w-max min-w-full",
      },
      both: {
        viewport: "overflow-auto",
        content: "w-max min-w-full",
      },
    },
  },
  defaultVariants: { orientation: "vertical" },
});

/** The width of the lane of a scrollbar, in pixels, for each size. Its thumb is 4 pixels less: the lane has 2 pixels of room on each side. */
export const scrollAreaSizes = { sm: 8, md: 10, lg: 14 } as const;

2. Add the Scroll Area file

src/components/ui/scroll-area/scroll-area.tsxShow code
"use client";

import {
  type CSSProperties,
  type PointerEvent,
  type ReactNode,
  type Ref,
  type UIEvent,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { cn } from "@/lib/cn";
import { scrollAreaSizes, scrollAreaStyles } from "@/types/scroll-area-styles";

type Axis = "vertical" | "horizontal";

interface AxisMetrics {
  /** Whether there is more content than room, on this axis. */
  hasOverflow: boolean;
  /** The length of the thumb, in pixels. */
  thumb: number;
  /** How far the thumb has moved along its lane, in pixels. */
  offset: number;
  /** The content is scrolled all the way to the start (top or left). */
  atStart: boolean;
  /** The content is scrolled all the way to the end (bottom or right). */
  atEnd: boolean;
}

const NO_OVERFLOW: AxisMetrics = {
  hasOverflow: false,
  thumb: 0,
  offset: 0,
  atStart: true,
  atEnd: true,
};

const MIN_THUMB = 24;
// The room around a thumb in its lane: the lane has `p-0.5` on each side.
const LANE_PADDING = 2;
const FADE_SIZE = 24;

function measure(
  client: number,
  scroll: number,
  position: number,
  lane: number,
): AxisMetrics {
  const max = scroll - client;
  if (max <= 1 || lane <= 0) return NO_OVERFLOW;
  const thumb = Math.min(lane, Math.max(MIN_THUMB, (lane * client) / scroll));
  const offset = Math.min(
    Math.max((position / max) * (lane - thumb), 0),
    lane - thumb,
  );
  return {
    hasOverflow: true,
    thumb: Math.round(thumb * 2) / 2,
    offset: Math.round(offset * 2) / 2,
    atStart: position <= 0.5,
    atEnd: position >= max - 0.5,
  };
}

const sameMetrics = (a: AxisMetrics, b: AxisMetrics) =>
  a.hasOverflow === b.hasOverflow &&
  a.thumb === b.thumb &&
  a.offset === b.offset &&
  a.atStart === b.atStart &&
  a.atEnd === b.atEnd;

export interface ScrollAreaProps {
  /** What scrolls. */
  children: ReactNode;
  /**
   * The way it scrolls: `vertical`, `horizontal`, or `both`. Defaults to `vertical`.
   * Give the area a size (a height for vertical, a width for horizontal, both
   * for `both`, or a `max-h-*`) with `className`: it scrolls when the content is
   * bigger than that.
   */
  orientation?: "vertical" | "horizontal" | "both";
  /**
   * When the scrollbars show. `hover` while the pointer is over the area or it is
   * scrolling, `scroll` only while it is scrolling, `always` whenever there is
   * more to scroll. Defaults to `hover`.
   */
  type?: "hover" | "scroll" | "always";
  /** How long the scrollbars stay after the pointer leaves or the scrolling stops, in milliseconds. Defaults to `600`. */
  scrollHideDelay?: number;
  /** How thick the scrollbars are. Defaults to `md`. */
  size?: "sm" | "md" | "lg";
  /** Fade the content at an edge that has more to scroll to, as a hint that there is more. Defaults to `false`. */
  hasFade?: boolean;
  /** Names the area for screen readers, and makes it a region a screen reader user can go to. */
  "aria-label"?: string;
  /** Called when the content scrolls. */
  onScroll?: (event: UIEvent<HTMLDivElement>) => void;
  /** The element that scrolls, to scroll it yourself: `ref.current.scrollTo({ top: 0 })`. */
  viewportRef?: Ref<HTMLDivElement>;
  /** Classes for the area: its size, its border, its shape. */
  className?: string;
  /** Classes for the scrolling element, such as padding for the content. */
  viewportClassName?: string;
}

/**
 * An area that scrolls, with scrollbars that look like the rest of the theme
 * and stay out of the way. The browser does the scrolling, so the wheel, touch,
 * the trackpad and the keyboard work as they always do; the scrollbars are drawn
 * over the content, take no room, and appear when they are needed.
 *
 * Use it for a list in a panel, a code block, a table, a chat, a long menu. The
 * scrollbar can be dragged, and a click in its lane goes there. When there is
 * more to scroll to, the area can be reached with Tab and scrolled with the
 * arrow keys, Page Up, Page Down, Home and End.
 *
 * @example
 * <ScrollArea className="h-72 w-64 rounded-xl border" aria-label="Tags">
 *   <ul className="p-4">...</ul>
 * </ScrollArea>
 */
export function ScrollArea({
  children,
  orientation = "vertical",
  type = "hover",
  scrollHideDelay = 600,
  size = "md",
  hasFade = false,
  "aria-label": ariaLabel,
  onScroll,
  viewportRef,
  className,
  viewportClassName,
}: ScrollAreaProps) {
  const styles = scrollAreaStyles({ orientation });
  const thickness = scrollAreaSizes[size];
  const showVertical = orientation !== "horizontal";
  const showHorizontal = orientation !== "vertical";

  const viewport = useRef<HTMLDivElement>(null);
  const content = useRef<HTMLDivElement>(null);
  useImperativeHandle(viewportRef, () => viewport.current as HTMLDivElement);

  const [vertical, setVertical] = useState(NO_OVERFLOW);
  const [horizontal, setHorizontal] = useState(NO_OVERFLOW);
  const [isActive, setIsActive] = useState(false);
  const [dragging, setDragging] = useState<Axis | null>(null);

  const update = useCallback(() => {
    const element = viewport.current;
    if (!element) return;
    // With both bars, a corner is kept free so that they do not cross.
    const corner = orientation === "both" ? thickness : 0;
    const next = {
      v: showVertical
        ? measure(
            element.clientHeight,
            element.scrollHeight,
            element.scrollTop,
            element.clientHeight - corner - LANE_PADDING * 2,
          )
        : NO_OVERFLOW,
      h: showHorizontal
        ? measure(
            element.clientWidth,
            element.scrollWidth,
            Math.abs(element.scrollLeft),
            element.clientWidth - corner - LANE_PADDING * 2,
          )
        : NO_OVERFLOW,
    };
    setVertical((prev) => (sameMetrics(prev, next.v) ? prev : next.v));
    setHorizontal((prev) => (sameMetrics(prev, next.h) ? prev : next.h));
  }, [orientation, thickness, showVertical, showHorizontal]);

  // Measured again when the area or what is in it changes size.
  useEffect(() => {
    update();
    const observer = new ResizeObserver(update);
    if (viewport.current) observer.observe(viewport.current);
    if (content.current) observer.observe(content.current);
    return () => observer.disconnect();
  }, [update]);

  // Showing and hiding. `keep` is set while something holds the scrollbars up:
  // the pointer over the area or a bar, or a thumb being dragged.
  const keep = useRef(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  const reveal = useCallback(() => {
    clearTimeout(timer.current);
    setIsActive(true);
  }, []);
  const hideLater = useCallback(() => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      if (!keep.current) setIsActive(false);
    }, scrollHideDelay);
  }, [scrollHideDelay]);

  function handleScroll(event: UIEvent<HTMLDivElement>) {
    update();
    if (type !== "always") {
      reveal();
      hideLater();
    }
    onScroll?.(event);
  }

  function handleRootPointerEnter(event: PointerEvent) {
    if (type !== "hover" || event.pointerType !== "mouse") return;
    keep.current = true;
    reveal();
  }
  function handleRootPointerLeave(event: PointerEvent) {
    if (type !== "hover" || event.pointerType !== "mouse") return;
    keep.current = dragging !== null;
    hideLater();
  }
  // The pointer over a bar holds it up, in every type: it is about to be used.
  function handleBarPointerEnter() {
    keep.current = true;
    reveal();
  }
  function handleBarPointerLeave() {
    if (dragging === null && type !== "hover") keep.current = false;
    hideLater();
  }

  // Dragging a thumb: the pointer is captured, so the drag goes on outside it.
  const drag = useRef<{
    axis: Axis;
    start: number;
    scroll: number;
    ratio: number;
  } | null>(null);

  function startDrag(axis: Axis, event: PointerEvent<HTMLDivElement>) {
    const element = viewport.current;
    if (!element || event.button !== 0) return;
    event.preventDefault();
    event.stopPropagation();
    const metrics = axis === "vertical" ? vertical : horizontal;
    const corner = orientation === "both" ? thickness : 0;
    const lane =
      (axis === "vertical" ? element.clientHeight : element.clientWidth) -
      corner -
      LANE_PADDING * 2;
    const max =
      axis === "vertical"
        ? element.scrollHeight - element.clientHeight
        : element.scrollWidth - element.clientWidth;
    event.currentTarget.setPointerCapture(event.pointerId);
    drag.current = {
      axis,
      start: axis === "vertical" ? event.clientY : event.clientX,
      scroll: axis === "vertical" ? element.scrollTop : element.scrollLeft,
      ratio: max / Math.max(lane - metrics.thumb, 1),
    };
    keep.current = true;
    reveal();
    setDragging(axis);
  }

  function moveDrag(event: PointerEvent<HTMLDivElement>) {
    const element = viewport.current;
    const current = drag.current;
    if (!element || !current) return;
    const delta =
      (current.axis === "vertical" ? event.clientY : event.clientX) -
      current.start;
    if (current.axis === "vertical")
      element.scrollTop = current.scroll + delta * current.ratio;
    else element.scrollLeft = current.scroll + delta * current.ratio;
  }

  function endDrag(event: PointerEvent<HTMLDivElement>) {
    if (!drag.current) return;
    drag.current = null;
    if (event.currentTarget.hasPointerCapture(event.pointerId))
      event.currentTarget.releasePointerCapture(event.pointerId);
    keep.current = false;
    setDragging(null);
    hideLater();
  }

  // A press in the empty part of a lane goes there: the thumb comes to the
  // pointer.
  function jumpTo(axis: Axis, event: PointerEvent<HTMLDivElement>) {
    const element = viewport.current;
    if (!element || event.button !== 0 || event.target !== event.currentTarget)
      return;
    const rect = event.currentTarget.getBoundingClientRect();
    const metrics = axis === "vertical" ? vertical : horizontal;
    const lane =
      (axis === "vertical" ? rect.height : rect.width) - LANE_PADDING * 2;
    const at =
      (axis === "vertical"
        ? event.clientY - rect.top
        : event.clientX - rect.left) -
      LANE_PADDING -
      metrics.thumb / 2;
    const share = Math.min(
      Math.max(at / Math.max(lane - metrics.thumb, 1), 0),
      1,
    );
    if (axis === "vertical")
      element.scrollTop = share * (element.scrollHeight - element.clientHeight);
    else
      element.scrollLeft = share * (element.scrollWidth - element.clientWidth);
  }

  const canScroll = vertical.hasOverflow || horizontal.hasOverflow;
  const isVisible = (hasOverflow: boolean) =>
    hasOverflow && (type === "always" || isActive || dragging !== null);

  // The fade at an edge that has more behind it: a mask on the scrolling element.
  const fade = (axis: Axis, metrics: AxisMetrics) => {
    const start = metrics.hasOverflow && !metrics.atStart ? FADE_SIZE : 0;
    const end = metrics.hasOverflow && !metrics.atEnd ? FADE_SIZE : 0;
    if (!start && !end) return null;
    return `linear-gradient(${axis === "vertical" ? "to bottom" : "to right"}, transparent 0, #000 ${start}px, #000 calc(100% - ${end}px), transparent 100%)`;
  };
  const masks = hasFade
    ? [fade("vertical", vertical), fade("horizontal", horizontal)].filter(
        (mask): mask is string => mask !== null,
      )
    : [];
  const maskStyle: CSSProperties | undefined = masks.length
    ? {
        maskImage: masks.join(", "),
        WebkitMaskImage: masks.join(", "),
        maskComposite: "intersect",
        WebkitMaskComposite: "source-in",
      }
    : undefined;

  const corner = orientation === "both" ? thickness : 0;

  return (
    <div
      className={cn(styles.root(), className)}
      onPointerEnter={handleRootPointerEnter}
      onPointerLeave={handleRootPointerLeave}
    >
      <div
        ref={viewport}
        // The area can be reached with Tab when there is more to scroll to, so
        // that it can be scrolled with the keyboard.
        tabIndex={canScroll ? 0 : undefined}
        {...(ariaLabel && canScroll
          ? { role: "region", "aria-label": ariaLabel }
          : {})}
        className={cn(styles.viewport(), viewportClassName)}
        style={maskStyle}
        onScroll={handleScroll}
      >
        <div ref={content} className={styles.content()}>
          {children}
        </div>
      </div>

      {showVertical ? (
        <div
          aria-hidden="true"
          data-visible={isVisible(vertical.hasOverflow)}
          className={styles.scrollbar()}
          style={{
            top: 0,
            right: 0,
            bottom: corner,
            width: thickness,
            flexDirection: "column",
          }}
          onPointerEnter={handleBarPointerEnter}
          onPointerLeave={handleBarPointerLeave}
          onPointerDown={(event) => jumpTo("vertical", event)}
        >
          <div
            data-dragging={dragging === "vertical"}
            className={cn(styles.thumb(), "w-full")}
            style={{
              height: vertical.thumb,
              transform: `translateY(${vertical.offset}px)`,
            }}
            onPointerDown={(event) => startDrag("vertical", event)}
            onPointerMove={moveDrag}
            onPointerUp={endDrag}
            onPointerCancel={endDrag}
          />
        </div>
      ) : null}

      {showHorizontal ? (
        <div
          aria-hidden="true"
          data-visible={isVisible(horizontal.hasOverflow)}
          className={styles.scrollbar()}
          style={{
            left: 0,
            bottom: 0,
            right: corner,
            height: thickness,
          }}
          onPointerEnter={handleBarPointerEnter}
          onPointerLeave={handleBarPointerLeave}
          onPointerDown={(event) => jumpTo("horizontal", event)}
        >
          <div
            data-dragging={dragging === "horizontal"}
            className={cn(styles.thumb(), "h-full")}
            style={{
              width: horizontal.thumb,
              transform: `translateX(${horizontal.offset}px)`,
            }}
            onPointerDown={(event) => startDrag("horizontal", event)}
            onPointerMove={moveDrag}
            onPointerUp={endDrag}
            onPointerCancel={endDrag}
          />
        </div>
      ) : null}
    </div>
  );
}

3. Use it

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

Anatomy

One component: the parts are made for you.

<ScrollArea className="h-72 w-64 rounded-xl border" aria-label="Tags">
  <ul className="p-4">...</ul>
</ScrollArea>
PartRendered asNotes
RootdivSets the size and the look of the area. It clips what is outside it.
ViewportdivThe element the browser scrolls, with its own scrollbar hidden. It can be reached with Tab when there is more to scroll to.
ScrollbardivA see-through lane along an edge, over the content. It takes no room, and is hidden from screen readers, as the viewport is what they scroll.
ThumbdivThe part that moves. It can be dragged.

Keyboard

These are the keys of the browser, on the area when it has focus.

KeyWhat it does
TabMoves to the area, when there is more in it to scroll to.
↑ ↓ ← →Scrolls a little.
Page Up, Page DownScrolls a page.
Home, EndGoes to the start or the end.
Space, Shift+SpaceScrolls a page down or up.

Examples

Usage

Point at the area or scroll it, and the scrollbar shows.

  • Accessibility
  • Animation
  • Authentication
  • Charts
  • Color
  • Components
  • Data
  • Design tokens
  • Documentation
  • Forms
  • Icons
  • Internationalization
  • Layout
  • Motion
  • Navigation
  • Overlays
  • Performance
  • Routing
  • Testing
  • Theming
  • Typography
  • Validation

Horizontal

A row that is wider than the room scrolls sideways.

Both ways

With both, a corner is kept free so that the two scrollbars do not cross.

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

When to show

type is when the scrollbars are shown. hover: while the pointer is over the area or it scrolls. scroll: only while it scrolls. always: whenever there is more to scroll to. The scrollbar stays while the pointer is on it, and scrollHideDelay is how long it stays after that.

  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
type="hover"
  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
type="scroll"
  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
type="always"

Sizes

  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
size="sm"
  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
size="md"
  • v2.4.0
  • v2.3.0
  • v2.2.0
  • v2.1.0
  • v2.0.0
  • v1.9.0
  • v1.8.0
  • v1.7.0
  • v1.6.0
  • v1.5.0
  • v1.4.0
  • v1.3.0
size="lg"

Fade

hasFade fades the edge that has more behind it, and stops when the end is reached. The scrollbar is not faded.

  • Accessibility
  • Animation
  • Authentication
  • Charts
  • Color
  • Components
  • Data
  • Design tokens
  • Documentation
  • Forms
  • Icons
  • Internationalization
  • Layout
  • Motion
  • Navigation
  • Overlays
  • Performance
  • Routing
  • Testing
  • Theming
  • Typography
  • Validation

Scroll it yourself

viewportRef is the element that scrolls, so it can be scrolled from code, and onScroll says where it is.

  • v2.4.0Scroll Area, Context Menu and Wallet
  • v2.3.0Color components and the theme chart
  • v2.2.0Date and time components
  • v2.1.0Visualization: area, bar, pie and radar charts
  • v2.0.0Rebuilt on react-aria-components
  • v1.9.0Toast and Tooltip
  • v1.8.0Sheet and Drawer
  • v1.7.0Tabs, Tree and Navbar
  • v1.6.0Number Field and Input OTP
  • v1.5.0Combobox and Autocomplete
  • v1.4.0Carousel
  • v1.3.0Pagination and Breadcrumbs
0%

Component API

ScrollArea takes the props below.

PropTypeDefault
childrenReactNode-
orientation"vertical" | "horizontal" | "both""vertical"
type"hover" | "scroll" | "always""hover"
scrollHideDelaynumber (ms)600
size"sm" | "md" | "lg""md"
hasFadebooleanfalse
aria-labelstring-
onScroll(event: UIEvent<HTMLDivElement>) => void-
viewportRefRef<HTMLDivElement>-
classNamestring-
viewportClassNamestring-