Skip to content

ComponentsUtilities

SourceSource

Scrollbar Utility

Discord-styled scrollbars for any scrollable container, with an overlay thumb, auto-hide and an optional keyboard-focusable viewport.

Discord-styled scrollbars for any scrollable container, with an overlay thumb, auto-hide and an optional keyboard-focusable viewport. Compose it from the exported registry parts so local content and behaviour stay in the application while the visual contract stays token-driven.

Root class newt-scrollbar
import { ScrollArea } from "@/registry/bases/newt/ui/scrollbar"

const messages = Array.from({ length: 24 }, (_, i) => `Message line ${i + 1}`)

export default function ScrollbarDemo() {
  return (
    <ScrollArea className="max-h-[240px] w-full max-w-sm overflow-y-auto rounded-md bg-newt-bg-elevated p-3">
      <ul className="flex flex-col gap-2 text-[14px] text-newt-text-secondary">
        {messages.map((m) => (
          <li key={m}>{m}</li>
        ))}
      </ul>
    </ScrollArea>
  )
}
<script setup lang="ts">
import { ScrollArea } from "~~/registry/bases/newt/ui/scrollbar"

const messages = Array.from({ length: 24 }, (_, i) => `Message line ${i + 1}`)
</script>

<template>
  <ScrollArea
    class="max-h-[240px] w-full max-w-sm overflow-y-auto rounded-md bg-newt-bg-elevated p-3"
  >
    <ul class="flex flex-col gap-2 text-[14px] text-newt-text-secondary">
      <li v-for="m in messages" :key="m">{{ m }}</li>
    </ul>
  </ScrollArea>
</template>

Installation

npx newtui@latest add scrollbarnpx shadcn@latest add @newtui/scrollbarnpx shadcn-vue@latest add @newtui/scrollbarpnpm dlx newtui@latest add scrollbarpnpm dlx shadcn@latest add @newtui/scrollbarpnpm dlx shadcn-vue@latest add @newtui/scrollbaryarn dlx newtui@latest add scrollbaryarn dlx shadcn@latest add @newtui/scrollbaryarn dlx shadcn-vue@latest add @newtui/scrollbarbunx newtui@latest add scrollbarbunx shadcn@latest add @newtui/scrollbarbunx shadcn-vue@latest add @newtui/scrollbardeno run -A npm:newtui@latest add scrollbardeno run -A npm:shadcn@latest add @newtui/scrollbardeno run -A npm:shadcn-vue@latest add @newtui/scrollbarvlx newtui@latest add scrollbarvlx shadcn@latest add @newtui/scrollbarvlx shadcn-vue@latest add @newtui/scrollbarvp dlx newtui@latest add scrollbarvp dlx shadcn@latest add @newtui/scrollbarvp dlx shadcn-vue@latest add @newtui/scrollbarnubx newtui@latest add scrollbarnubx shadcn@latest add @newtui/scrollbarnubx shadcn-vue@latest add @newtui/scrollbarnlx newtui@latest add scrollbarnlx shadcn@latest add @newtui/scrollbarnlx shadcn-vue@latest add @newtui/scrollbarupx newtui@latest add scrollbarupx shadcn@latest add @newtui/scrollbarupx shadcn-vue@latest add @newtui/scrollbar

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Copy the source into your project

/*
 * No "use client" here: a Server Component imports the class strings as
 * strings. Only `ScrollArea`, which runs hooks, is a client component.
 */
export {
  ScrollArea,
  ScrollArea as Scrollbar,
  type ScrollAreaProps,
} from "@/registry/bases/newt/ui/scroll-area"
export {
  scrollbarAutoHideClassName,
  scrollbarClassName,
} from "@/registry/bases/newt/ui/scrollbar-classes"
"use client"

import * as React from "react"

import { cn } from "@/lib/utils"
import {
  scrollbarAutoHideClassName,
  scrollbarClassName,
} from "@/registry/bases/newt/ui/scrollbar-classes"

/*
 * A focusable region shows its focus inside its own box, where an ancestor
 * with `overflow: hidden` cannot clip it.
 */
const focusRingClassName =
  "focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link"

/** How long an auto-hiding thumb stays after the last scroll, in ms. */
const HIDE_DELAY = 800

/**
 * Wires the behaviour CSS cannot express and returns its teardown. The
 * viewport scrolls natively, so the keyboard, the wheel and touch need nothing
 * from here. `root` is the element that carries `data-scrolling`.
 */
function attachScrollbar(
  root: HTMLElement,
  viewport: HTMLElement,
  autoHide: boolean,
  overlay?: { track: HTMLElement; thumb: HTMLElement }
): () => void {
  const abort = new AbortController()
  const { signal } = abort
  let drag: { y: number; scrollTop: number; ratio: number } | undefined
  let hideTimer: ReturnType<typeof setTimeout> | undefined

  /*
   * Hover and focus are the stylesheet's. This covers a scroll that neither
   * explains, such as a new message or a touch.
   */
  function showWhileScrolling() {
    if (!autoHide) return
    root.setAttribute("data-scrolling", "")
    clearTimeout(hideTimer)
    if (drag) return
    hideTimer = setTimeout(
      () => root.removeAttribute("data-scrolling"),
      HIDE_DELAY
    )
  }

  viewport.addEventListener("scroll", showWhileScrolling, {
    passive: true,
    signal,
  })

  if (overlay) {
    const { track, thumb } = overlay

    const draw = () => {
      const overflow = viewport.scrollHeight - viewport.clientHeight
      track.hidden = overflow < 1
      if (track.hidden) return
      const length = track.clientHeight
      thumb.style.height = `${(viewport.clientHeight / viewport.scrollHeight) * length}px`
      // The classes cap the height, so the travel is read back from the box.
      const travel = Math.max(0, length - thumb.offsetHeight)
      thumb.style.transform = `translateY(${(viewport.scrollTop / overflow) * travel}px)`
    }

    viewport.addEventListener("scroll", draw, { passive: true, signal })

    /*
     * The content has no wrapper to measure, so each child is watched:
     * content that grows or shrinks changes the size of one of them.
     */
    const resize = new ResizeObserver(draw)
    const watch = () => {
      resize.disconnect()
      for (const element of [viewport, track, ...viewport.children]) {
        resize.observe(element)
      }
    }
    /*
     * A new child needs watching. A changed text node resizes nothing that is
     * watched when it sits straight in the viewport, so it redraws.
     */
    const mutation = new MutationObserver((records) => {
      if (
        records.some((r) => r.type === "childList" && r.target === viewport)
      ) {
        watch()
      } else {
        draw()
      }
    })
    mutation.observe(viewport, {
      childList: true,
      characterData: true,
      subtree: true,
    })
    watch()
    signal.addEventListener("abort", () => {
      resize.disconnect()
      mutation.disconnect()
    })

    /*
     * Each pixel the thumb moves is worth as much scroll as the content is
     * longer than the thumb's travel, which is how a native bar drags.
     */
    thumb.addEventListener(
      "pointerdown",
      (event) => {
        if (event.button !== 0) return
        event.preventDefault()
        const travel = track.clientHeight - thumb.offsetHeight
        if (travel <= 0) return
        thumb.setPointerCapture(event.pointerId)
        drag = {
          y: event.clientY,
          scrollTop: viewport.scrollTop,
          ratio: (viewport.scrollHeight - viewport.clientHeight) / travel,
        }
        showWhileScrolling()
      },
      { signal }
    )
    thumb.addEventListener(
      "pointermove",
      (event) => {
        if (!drag) return
        viewport.scrollTop =
          drag.scrollTop + (event.clientY - drag.y) * drag.ratio
      },
      { signal }
    )
    thumb.addEventListener(
      "lostpointercapture",
      () => {
        drag = undefined
        showWhileScrolling()
      },
      { signal }
    )
  }

  return () => {
    abort.abort()
    clearTimeout(hideTimer)
    root.removeAttribute("data-scrolling")
  }
}

export interface ScrollAreaProps extends React.ComponentProps<"div"> {
  /**
   * `native` styles the browser's scrollbar, which keeps a lane beside the
   * content. `overlay` draws a thumb over the content instead, so the box
   * keeps its full width. It scrolls on the block axis only, and renders an
   * outer box around the viewport: `className`, `style` and `dir` land on the
   * box, every other attribute and the ref on the viewport, which is the
   * element that scrolls.
   */
  variant?: "native" | "overlay"
  /**
   * Hide the thumb until the pointer is over the area, keyboard focus is
   * inside it, or it scrolls.
   */
  autoHide?: boolean
  /**
   * Put the viewport in the tab order so it can be scrolled from the keyboard
   * (WCAG 2.1.1). Off by default: a focusable region only helps when the area
   * actually scrolls and holds no other focusable content.
   */
  focusable?: boolean
  /** Accessible name of the focusable viewport. */
  viewportLabel?: string
  /**
   * Classes for the element that scrolls. With `overlay`, padding that should
   * scroll with the content belongs here.
   */
  viewportClassName?: string
}

const ScrollArea = React.forwardRef<HTMLDivElement, ScrollAreaProps>(
  (
    {
      className,
      variant = "native",
      autoHide = false,
      focusable = false,
      viewportLabel = "Scrollable region",
      viewportClassName,
      style,
      dir,
      ...props
    },
    ref
  ) => {
    const overlay = variant === "overlay"
    const root = React.useRef<HTMLDivElement | null>(null)
    const viewport = React.useRef<HTMLDivElement | null>(null)
    const track = React.useRef<HTMLDivElement | null>(null)
    const thumb = React.useRef<HTMLDivElement | null>(null)
    React.useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(
      ref,
      () => viewport.current
    )

    React.useEffect(() => {
      if (!viewport.current || (!overlay && !autoHide)) return
      return attachScrollbar(
        root.current ?? viewport.current,
        viewport.current,
        autoHide,
        track.current && thumb.current
          ? { track: track.current, thumb: thumb.current }
          : undefined
      )
    }, [overlay, autoHide])

    if (!overlay) {
      return (
        <div
          ref={viewport}
          tabIndex={focusable ? 0 : undefined}
          role={focusable ? "group" : undefined}
          aria-label={focusable ? viewportLabel : undefined}
          dir={dir}
          style={style}
          className={cn(
            "overflow-auto",
            scrollbarClassName,
            autoHide && scrollbarAutoHideClassName,
            focusRingClassName,
            viewportClassName,
            className
          )}
          {...props}
        />
      )
    }

    return (
      <div
        ref={root}
        dir={dir}
        style={style}
        className={cn(
          "relative flex flex-col",
          autoHide &&
            "[&:not(:hover):not(:has(:focus-visible)):not([data-scrolling])>[data-scrollbar-track]]:invisible",
          className
        )}
      >
        <div
          ref={viewport}
          tabIndex={focusable ? 0 : undefined}
          role={focusable ? "group" : undefined}
          aria-label={focusable ? viewportLabel : undefined}
          className={cn(
            "min-h-0 flex-1 overflow-y-auto overflow-x-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
            focusRingClassName,
            viewportClassName
          )}
          {...props}
        />
        {/*
         * Only the thumb takes the pointer, so the content under the track
         * stays clickable. Hidden until the content overflows.
         */}
        <div
          ref={track}
          data-scrollbar-track=""
          aria-hidden="true"
          hidden
          className="pointer-events-none absolute bottom-[var(--newt-scrollbar-inset-end,4px)] end-1 top-[var(--newt-scrollbar-inset-start,4px)]"
        >
          <div
            ref={thumb}
            className="pointer-events-auto max-h-[var(--newt-scrollbar-thumb-max-height,none)] min-h-[min(24px,100%)] w-[var(--newt-scrollbar-thumb-width,8px)] touch-none rounded-full bg-[var(--newt-scrollbar-thumb,var(--newt-bg-active))] hover:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))] active:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))]"
          />
        </div>
      </div>
    )
  }
)
ScrollArea.displayName = "ScrollArea"

export { ScrollArea }
/**
 * Tailwind classes that give any scrollable container Discord-styled
 * scrollbars (thin, rounded thumb, transparent track). Apply via
 * `<ScrollArea>` or spread `scrollbarClassName` on your own element.
 *
 * The thumb reads `--newt-scrollbar-thumb` and, under the pointer,
 * `--newt-scrollbar-thumb-hover`. Set either on the element or an ancestor.
 */
export const scrollbarClassName = [
  "[scrollbar-width:thin] [scrollbar-color:var(--newt-scrollbar-thumb,var(--newt-bg-active))_transparent]",
  "[&::-webkit-scrollbar]:h-4 [&::-webkit-scrollbar]:w-4",
  "[&::-webkit-scrollbar-track]:bg-transparent",
  "[&::-webkit-scrollbar-thumb]:rounded-[var(--newt-radius-lg)] [&::-webkit-scrollbar-thumb]:border-4 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-[var(--newt-scrollbar-thumb,var(--newt-bg-active))] [&::-webkit-scrollbar-thumb]:bg-clip-padding",
  "[&::-webkit-scrollbar-thumb:hover]:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))] [&::-webkit-scrollbar-thumb:hover]:bg-clip-padding",
  "[&::-webkit-scrollbar-corner]:bg-transparent",
].join(" ")

/**
 * Add next to `scrollbarClassName` to hide the thumb until the pointer is
 * over the element or keyboard focus is inside it. Set `data-scrolling` on
 * the element to show it for any other reason; `<ScrollArea autoHide>` does
 * that while the area scrolls.
 */
export const scrollbarAutoHideClassName = [
  "[&:not(:hover):not(:focus-visible):not(:has(:focus-visible)):not([data-scrolling])]:[scrollbar-color:transparent_transparent]",
  "[&:not(:hover):not(:focus-visible):not(:has(:focus-visible)):not([data-scrolling])::-webkit-scrollbar-thumb]:bg-transparent",
].join(" ")
<script setup lang="ts">
import {
  useTemplateRef,
  watchEffect,
  type HTMLAttributes,
  type StyleValue,
} from "vue"

import { cn } from "@/lib/utils"

import { scrollbarAutoHideClassName, scrollbarClassName } from "."

/*
 * `class`, `style` and `dir` land on the outer box. Every other attribute
 * lands on the viewport, which is the element that scrolls. The two are one
 * element unless `variant` is `overlay`.
 */
defineOptions({ inheritAttrs: false })

const props = withDefaults(
  defineProps<{
    class?: HTMLAttributes["class"]
    style?: StyleValue
    dir?: HTMLAttributes["dir"]
    /**
     * `native` styles the browser's scrollbar, which keeps a lane beside the
     * content. `overlay` draws a thumb over the content instead, so the box
     * keeps its full width. It scrolls on the block axis only, and renders an
     * outer box around the viewport.
     */
    variant?: "native" | "overlay"
    /**
     * Hide the thumb until the pointer is over the area, keyboard focus is
     * inside it, or it scrolls.
     */
    autoHide?: boolean
    /**
     * Put the viewport in the tab order so it can be scrolled from the keyboard
     * (WCAG 2.1.1). Off by default: a focusable region only helps when the area
     * actually scrolls and holds no other focusable content.
     */
    focusable?: boolean
    /** Accessible name of the focusable viewport. */
    viewportLabel?: string
    /**
     * Classes for the element that scrolls. With `overlay`, padding that
     * should scroll with the content belongs here.
     */
    viewportClass?: HTMLAttributes["class"]
  }>(),
  { variant: "native", viewportLabel: "Scrollable region" }
)

/*
 * A focusable region shows its focus inside its own box, where an ancestor
 * with `overflow: hidden` cannot clip it.
 */
const focusRingClassName =
  "focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-newt-text-link"

/** How long an auto-hiding thumb stays after the last scroll, in ms. */
const HIDE_DELAY = 800

const root = useTemplateRef<HTMLDivElement>("root")
const viewport = useTemplateRef<HTMLDivElement>("viewport")
const track = useTemplateRef<HTMLDivElement>("track")
const thumb = useTemplateRef<HTMLDivElement>("thumb")

/** The element that scrolls, to read or set its scroll position. */
defineExpose({ viewport })

/**
 * Wires the behaviour CSS cannot express and returns its teardown. The
 * viewport scrolls natively, so the keyboard, the wheel and touch need nothing
 * from here. `box` is the element that carries `data-scrolling`.
 */
function attachScrollbar(
  box: HTMLElement,
  scroller: HTMLElement,
  autoHide: boolean,
  overlay?: { track: HTMLElement; thumb: HTMLElement }
): () => void {
  const abort = new AbortController()
  const { signal } = abort
  let drag: { y: number; scrollTop: number; ratio: number } | undefined
  let hideTimer: ReturnType<typeof setTimeout> | undefined

  /*
   * Hover and focus are the stylesheet's. This covers a scroll that neither
   * explains, such as a new message or a touch.
   */
  function showWhileScrolling() {
    if (!autoHide) return
    box.setAttribute("data-scrolling", "")
    clearTimeout(hideTimer)
    if (drag) return
    hideTimer = setTimeout(
      () => box.removeAttribute("data-scrolling"),
      HIDE_DELAY
    )
  }

  scroller.addEventListener("scroll", showWhileScrolling, {
    passive: true,
    signal,
  })

  if (overlay) {
    const { track: rail, thumb: handle } = overlay

    const draw = () => {
      const overflow = scroller.scrollHeight - scroller.clientHeight
      rail.hidden = overflow < 1
      if (rail.hidden) return
      const length = rail.clientHeight
      handle.style.height = `${(scroller.clientHeight / scroller.scrollHeight) * length}px`
      // The classes cap the height, so the travel is read back from the box.
      const travel = Math.max(0, length - handle.offsetHeight)
      handle.style.transform = `translateY(${(scroller.scrollTop / overflow) * travel}px)`
    }

    scroller.addEventListener("scroll", draw, { passive: true, signal })

    /*
     * The content has no wrapper to measure, so each child is watched:
     * content that grows or shrinks changes the size of one of them.
     */
    const resize = new ResizeObserver(draw)
    const watch = () => {
      resize.disconnect()
      for (const element of [scroller, rail, ...scroller.children]) {
        resize.observe(element)
      }
    }
    /*
     * A new child needs watching. A changed text node resizes nothing that is
     * watched when it sits straight in the viewport, so it redraws.
     */
    const mutation = new MutationObserver((records) => {
      if (
        records.some((r) => r.type === "childList" && r.target === scroller)
      ) {
        watch()
      } else {
        draw()
      }
    })
    mutation.observe(scroller, {
      childList: true,
      characterData: true,
      subtree: true,
    })
    watch()
    signal.addEventListener("abort", () => {
      resize.disconnect()
      mutation.disconnect()
    })

    /*
     * Each pixel the thumb moves is worth as much scroll as the content is
     * longer than the thumb's travel, which is how a native bar drags.
     */
    handle.addEventListener(
      "pointerdown",
      (event) => {
        if (event.button !== 0) return
        event.preventDefault()
        const travel = rail.clientHeight - handle.offsetHeight
        if (travel <= 0) return
        handle.setPointerCapture(event.pointerId)
        drag = {
          y: event.clientY,
          scrollTop: scroller.scrollTop,
          ratio: (scroller.scrollHeight - scroller.clientHeight) / travel,
        }
        showWhileScrolling()
      },
      { signal }
    )
    handle.addEventListener(
      "pointermove",
      (event) => {
        if (!drag) return
        scroller.scrollTop =
          drag.scrollTop + (event.clientY - drag.y) * drag.ratio
      },
      { signal }
    )
    handle.addEventListener(
      "lostpointercapture",
      () => {
        drag = undefined
        showWhileScrolling()
      },
      { signal }
    )
  }

  return () => {
    abort.abort()
    clearTimeout(hideTimer)
    box.removeAttribute("data-scrolling")
  }
}

watchEffect(
  (onCleanup) => {
    const scroller = viewport.value
    if (!scroller || (props.variant !== "overlay" && !props.autoHide)) return
    onCleanup(
      attachScrollbar(
        root.value ?? scroller,
        scroller,
        props.autoHide,
        track.value && thumb.value
          ? { track: track.value, thumb: thumb.value }
          : undefined
      )
    )
  },
  { flush: "post" }
)
</script>

<template>
  <div
    v-if="props.variant === 'overlay'"
    ref="root"
    :dir="props.dir"
    :style="props.style"
    :class="
      cn(
        'relative flex flex-col',
        props.autoHide &&
          '[&:not(:hover):not(:has(:focus-visible)):not([data-scrolling])>[data-scrollbar-track]]:invisible',
        props.class
      )
    "
  >
    <div
      ref="viewport"
      :tabindex="props.focusable ? 0 : undefined"
      :role="props.focusable ? 'group' : undefined"
      :aria-label="props.focusable ? props.viewportLabel : undefined"
      v-bind="$attrs"
      :class="
        cn(
          'min-h-0 flex-1 overflow-y-auto overflow-x-hidden [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',
          focusRingClassName,
          props.viewportClass
        )
      "
    >
      <slot />
    </div>
    <!--
      Only the thumb takes the pointer, so the content under the track stays
      clickable. Hidden until the content overflows.
    -->
    <div
      ref="track"
      data-scrollbar-track
      aria-hidden="true"
      hidden
      class="pointer-events-none absolute bottom-[var(--newt-scrollbar-inset-end,4px)] end-1 top-[var(--newt-scrollbar-inset-start,4px)]"
    >
      <div
        ref="thumb"
        class="pointer-events-auto max-h-[var(--newt-scrollbar-thumb-max-height,none)] min-h-[min(24px,100%)] w-[var(--newt-scrollbar-thumb-width,8px)] touch-none rounded-full bg-[var(--newt-scrollbar-thumb,var(--newt-bg-active))] hover:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))] active:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))]"
      />
    </div>
  </div>
  <div
    v-else
    ref="viewport"
    :tabindex="props.focusable ? 0 : undefined"
    :role="props.focusable ? 'group' : undefined"
    :aria-label="props.focusable ? props.viewportLabel : undefined"
    :dir="props.dir"
    :style="props.style"
    v-bind="$attrs"
    :class="
      cn(
        'overflow-auto',
        scrollbarClassName,
        props.autoHide && scrollbarAutoHideClassName,
        focusRingClassName,
        props.viewportClass,
        props.class
      )
    "
  >
    <slot />
  </div>
</template>
export { default as ScrollArea } from "./ScrollArea.vue"

/**
 * Tailwind classes that give any scrollable container Discord-styled
 * scrollbars (thin, rounded thumb, transparent track).
 *
 * The thumb reads `--newt-scrollbar-thumb` and, under the pointer,
 * `--newt-scrollbar-thumb-hover`. Set either on the element or an ancestor.
 */
export const scrollbarClassName = [
  "[scrollbar-width:thin] [scrollbar-color:var(--newt-scrollbar-thumb,var(--newt-bg-active))_transparent]",
  "[&::-webkit-scrollbar]:h-4 [&::-webkit-scrollbar]:w-4",
  "[&::-webkit-scrollbar-track]:bg-transparent",
  "[&::-webkit-scrollbar-thumb]:rounded-[var(--newt-radius-lg)] [&::-webkit-scrollbar-thumb]:border-4 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-[var(--newt-scrollbar-thumb,var(--newt-bg-active))] [&::-webkit-scrollbar-thumb]:bg-clip-padding",
  "[&::-webkit-scrollbar-thumb:hover]:bg-[var(--newt-scrollbar-thumb-hover,var(--newt-text-muted))] [&::-webkit-scrollbar-thumb:hover]:bg-clip-padding",
  "[&::-webkit-scrollbar-corner]:bg-transparent",
].join(" ")

/**
 * Add next to `scrollbarClassName` to hide the thumb until the pointer is
 * over the element or keyboard focus is inside it. Set `data-scrolling` on
 * the element to show it for any other reason; `<ScrollArea auto-hide>` does
 * that while the area scrolls.
 */
export const scrollbarAutoHideClassName = [
  "[&:not(:hover):not(:focus-visible):not(:has(:focus-visible)):not([data-scrolling])]:[scrollbar-color:transparent_transparent]",
  "[&:not(:hover):not(:focus-visible):not(:has(:focus-visible)):not([data-scrolling])::-webkit-scrollbar-thumb]:bg-transparent",
].join(" ")

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Scrollbar Utility to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Scrollbar Utility to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { Scrollbar } from "@/components/ui/scrollbar"

export function Example() {
  return <Scrollbar />
}
<script setup lang="ts">
import { ScrollArea } from "@/components/ui/scrollbar"
</script>

<template>
  <ScrollArea />
</template>

ScrollArea styles the browser’s own scrollbar by default. To style an element of your own, add scrollbarClassName to its classes.

Examples

Overlay

variant="overlay" draws the thumb over the content. The box keeps its full width, which suits a narrow column. Only the thumb takes the pointer, so the content under the track stays clickable.

The overlay variant renders an outer box around the viewport. The viewport is the element that scrolls. className, style and dir land on the box. Every other attribute lands on the viewport, and so does the React ref. Put padding that should scroll with the content in viewportClassName (viewport-class in Vue).

Give the box a height or a maximum height. The overlay variant scrolls on the block axis only. Use the native variant for content that scrolls sideways.

Here a card floats over the foot of the column. --newt-scrollbar-inset-end stops the track above it.

Root class newt-scrollbar
import { ScrollArea } from "@/registry/bases/newt/ui/scrollbar"

const channels = [
  "welcome",
  "rules",
  "announcements",
  "general",
  "introductions",
  "help",
  "showcase",
  "feedback",
  "off-topic",
  "music",
  "art",
  "events",
  "suggestions",
  "dev-log",
  "releases",
  "lounge",
]

/*
 * A column with a card floating over its foot. The thumb is drawn over the
 * rows, so they keep the full width, and the track stops above the card.
 */
export default function ScrollbarOverlayDemo() {
  return (
    <div className="relative w-full max-w-[240px]">
      <ScrollArea
        variant="overlay"
        focusable
        viewportLabel="Channels"
        className="h-[240px] rounded-md bg-newt-bg-surface [--newt-scrollbar-inset-end:60px]"
        viewportClassName="p-2 pb-[60px]"
      >
        <ul className="flex flex-col gap-0.5 text-[14px] text-newt-text-secondary">
          {channels.map((channel) => (
            <li
              key={channel}
              className="rounded-sm px-2 py-1.5 hover:bg-newt-bg-hover"
            >
              # {channel}
            </li>
          ))}
        </ul>
      </ScrollArea>
      <p className="absolute inset-x-2 bottom-2 rounded-md bg-newt-bg-floating px-3 py-2.5 text-[13px] font-medium text-newt-text-primary shadow-elevation-low">
        Riley is online
      </p>
    </div>
  )
}
<script setup lang="ts">
import { ScrollArea } from "~~/registry/bases/newt/ui/scrollbar"

const channels = [
  "welcome",
  "rules",
  "announcements",
  "general",
  "introductions",
  "help",
  "showcase",
  "feedback",
  "off-topic",
  "music",
  "art",
  "events",
  "suggestions",
  "dev-log",
  "releases",
  "lounge",
]
</script>

<template>
  <!--
    A column with a card floating over its foot. The thumb is drawn over the
    rows, so they keep the full width, and the track stops above the card.
  -->
  <div class="relative w-full max-w-[240px]">
    <ScrollArea
      variant="overlay"
      focusable
      viewport-label="Channels"
      class="h-[240px] rounded-md bg-newt-bg-surface [--newt-scrollbar-inset-end:60px]"
      viewport-class="p-2 pb-[60px]"
    >
      <ul class="flex flex-col gap-0.5 text-[14px] text-newt-text-secondary">
        <li
          v-for="channel in channels"
          :key="channel"
          class="rounded-sm px-2 py-1.5 hover:bg-newt-bg-hover"
        >
          # {{ channel }}
        </li>
      </ul>
    </ScrollArea>
    <p
      class="absolute inset-x-2 bottom-2 rounded-md bg-newt-bg-floating px-3 py-2.5 text-[13px] font-medium text-newt-text-primary shadow-elevation-low"
    >
      Riley is online
    </p>
  </div>
</template>

Auto-hide

autoHide hides the thumb until the pointer is over the area, keyboard focus is inside it, or it scrolls. It works with both variants. The rail below also sets --newt-scrollbar-thumb-width and --newt-scrollbar-thumb-max-height for a short, thin thumb.

Root class newt-scrollbar
import { ScrollArea } from "@/registry/bases/newt/ui/scrollbar"

const servers = ["NU", "DS", "QA", "UX", "OP", "DX", "IO", "FX"]
const messages = Array.from({ length: 24 }, (_, i) => `Message line ${i + 1}`)

/*
 * Both thumbs stay hidden until the pointer is over their area, keyboard
 * focus is inside it, or it scrolls. The rail draws a short, thin overlay
 * thumb; the log keeps the native scrollbar.
 */
export default function ScrollbarAutoHideDemo() {
  return (
    <div className="flex h-[240px] w-full max-w-sm overflow-hidden rounded-md bg-newt-bg-elevated">
      <ScrollArea
        variant="overlay"
        autoHide
        focusable
        viewportLabel="Servers"
        className="w-[72px] shrink-0 bg-newt-bg-base [--newt-scrollbar-thumb-max-height:48px] [--newt-scrollbar-thumb-width:4px]"
        viewportClassName="flex flex-col items-center gap-2 py-3"
      >
        {servers.map((server) => (
          <span
            key={server}
            className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-newt-bg-surface text-[14px] font-semibold text-newt-text-primary"
          >
            {server}
          </span>
        ))}
      </ScrollArea>
      <ScrollArea
        autoHide
        focusable
        viewportLabel="Messages"
        className="min-w-0 flex-1 p-3"
      >
        <ul className="flex flex-col gap-2 text-[14px] text-newt-text-secondary">
          {messages.map((message) => (
            <li key={message}>{message}</li>
          ))}
        </ul>
      </ScrollArea>
    </div>
  )
}
<script setup lang="ts">
import { ScrollArea } from "~~/registry/bases/newt/ui/scrollbar"

const servers = ["NU", "DS", "QA", "UX", "OP", "DX", "IO", "FX"]
const messages = Array.from({ length: 24 }, (_, i) => `Message line ${i + 1}`)
</script>

<template>
  <!--
    Both thumbs stay hidden until the pointer is over their area, keyboard
    focus is inside it, or it scrolls. The rail draws a short, thin overlay
    thumb; the log keeps the native scrollbar.
  -->
  <div
    class="flex h-[240px] w-full max-w-sm overflow-hidden rounded-md bg-newt-bg-elevated"
  >
    <ScrollArea
      variant="overlay"
      auto-hide
      focusable
      viewport-label="Servers"
      class="w-[72px] shrink-0 bg-newt-bg-base [--newt-scrollbar-thumb-max-height:48px] [--newt-scrollbar-thumb-width:4px]"
      viewport-class="flex flex-col items-center gap-2 py-3"
    >
      <span
        v-for="server in servers"
        :key="server"
        class="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-newt-bg-surface text-[14px] font-semibold text-newt-text-primary"
      >
        {{ server }}
      </span>
    </ScrollArea>
    <ScrollArea
      auto-hide
      focusable
      viewport-label="Messages"
      class="min-w-0 flex-1 p-3"
    >
      <ul class="flex flex-col gap-2 text-[14px] text-newt-text-secondary">
        <li v-for="m in messages" :key="m">{{ m }}</li>
      </ul>
    </ScrollArea>
  </div>
</template>

To auto-hide the scrollbar of your own element, add scrollbarAutoHideClassName next to scrollbarClassName. That class set reacts to hover and keyboard focus. Set data-scrolling on the element to show the thumb for any other reason.

API reference

ScrollArea

PropType
variant?"native" | "overlay"

`native` styles the browser's scrollbar, which keeps a lane beside the content. `overlay` draws a thumb over the content.

Type"native" | "overlay"
Default"native"
autoHide?boolean | undefined

Hide the thumb until the pointer is over the area, keyboard focus is inside it, or it scrolls.

Typeboolean | undefined
Defaultfalse
focusable?boolean | undefined

Put the viewport in the tab order so it can be scrolled from the keyboard (WCAG 2.1.1). Off by default: a focusable region only helps when the area actually scrolls and holds no other focusable content.

Typeboolean | undefined
viewportLabel?string | undefined

Accessible name of the focusable viewport.

Typestring | undefined
viewportClassName / viewportClass?string

Classes for the element that scrolls. With `overlay`, padding that should scroll with the content belongs here.

Typestring

The registry exports ScrollArea, Scrollbar, scrollbarClassName and scrollbarAutoHideClassName. Parts without a table accept the native attributes for the element they render; React uses className, while Vue uses class and fallthrough attributes. In Vue, ScrollArea exposes viewport, the element that scrolls.

Custom properties

Set these on the scroll area or on any ancestor. Each one is optional.

PropType
--newt-scrollbar-thumb?color

Colour of the thumb.

Typecolor
Defaultvar(--newt-bg-active)
--newt-scrollbar-thumb-hover?color

Colour of the thumb under the pointer.

Typecolor
Defaultvar(--newt-text-muted)
--newt-scrollbar-inset-start?length

Overlay only. Gap between the top of the box and the track.

Typelength
Default4px
--newt-scrollbar-inset-end?length

Overlay only. Gap between the track and the foot of the box.

Typelength
Default4px
--newt-scrollbar-thumb-width?length

Overlay only. Thickness of the thumb.

Typelength
Default8px
--newt-scrollbar-thumb-max-height?length

Overlay only. Longest the thumb can be.

Typelength
Defaultnone

Accessibility

The viewport scrolls natively in both variants. The keyboard, the wheel and touch work as they do on any scrolling element. The overlay thumb is decoration for assistive technology and carries aria-hidden.

The focusable viewport takes its name from viewportLabel. Translating labels lists every English default.

Set focusable when the area scrolls and holds no other focusable content. The viewport then takes tabindex="0", role="group" and the viewportLabel. Its focus ring is drawn inside the box, so an ancestor with overflow: hidden cannot clip it.

An auto-hidden thumb also shows on keyboard focus, so a keyboard user sees the scroll position. Preserve the native semantics of the rendered elements and pass through ARIA attributes when the surrounding context needs a label or description.

In the plain HTML and CSS distribution, the overlay thumb and the scroll state of newt-scrollbar--auto-hide need scrollbar.js. Mark the element with data-newt-scrollbar.

Tokens

Scrollbar Utility reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-scrollbar.

  • --newt-bg-active
  • --newt-text-muted
  • --newt-text-link
  • --newt-radius-full