← Components

Selection and input · Material 3: Sliders

Slider

Pick a value or range by dragging. The thumb stretches with fast drags; two close thumbs melt into one bubble.

Examples and variants

Single value

Drag or use arrow keys.

Example
function SliderSingle() {
  return (
    <div className="w-full max-w-xs">
      <Slider defaultValue={[40]} aria-label="Volume" />
    </div>
  )
}

Range

Two thumbs. Bring them close to see the bubbles merge.

Example
function SliderRange() {
  return (
    <div className="w-full max-w-xs">
      <Slider defaultValue={[20, 70]} aria-label="Price range" />
    </div>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/slider.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react cn
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/slider.tsxslider
      components/ui/slider.tsx
      "use client"
      
      import * as React from "react"
      import { Slider as SliderPrimitive } from "@base-ui/react/slider"
      import { cn } from "cn"
      import { GooLayer } from "@/components/motion/goo-layer"
      
      function Slider({
        className,
        defaultValue,
        value,
        min = 0,
        max = 100,
        onValueChange,
        onPointerMove,
        onPointerUp,
        onKeyUp,
        onBlur,
        ...props
      }: SliderPrimitive.Root.Props) {
        const _values = Array.isArray(value)
          ? value
          : Array.isArray(defaultValue)
            ? defaultValue
            : [min]
        const rootRef = React.useRef<HTMLDivElement>(null)
        const [live, setLive] = React.useState<readonly number[]>(_values)
        const [held, setHeld] = React.useState(false)
        const [stretch, setStretch] = React.useState(1)
        const [lag, setLag] = React.useState(0)
        const [merge, setMerge] = React.useState<{ left: number; top: number } | null>(null)
      
        React.useLayoutEffect(() => {
          const root = rootRef.current
          if (!root || live.length < 2) return
          const measure = () => {
            const thumbs = [...root.querySelectorAll<HTMLElement>("[data-slot=slider-thumb]")]
            if (thumbs.length < 2) return
            const first = thumbs[0].getBoundingClientRect()
            const second = thumbs[1].getBoundingClientRect()
            if (first.width === 0 || Math.abs(first.left - second.left) < 1) return
            const rootBox = root.getBoundingClientRect()
            const gap = second.left - first.right
            if (gap > first.width) {
              setMerge(null)
              return
            }
            setMerge({
              left: (first.left + second.right) / 2 - rootBox.left,
              top: first.top - rootBox.top,
            })
          }
          measure()
          const observer = new ResizeObserver(measure)
          observer.observe(root)
          return () => observer.disconnect()
        }, [live])
      
        return (
          <SliderPrimitive.Root
            className={cn("relative w-full py-6", className)}
            data-slot="slider"
            defaultValue={defaultValue}
            value={value}
            min={min}
            max={max}
            {...props}
            onValueChange={(next, eventDetails) => {
              setLive(Array.isArray(next) ? next : [next])
              setHeld(true)
              onValueChange?.(next, eventDetails)
            }}
            onPointerMove={(event) => {
              onPointerMove?.(event)
              if (event.buttons === 0) return
              const styles = getComputedStyle(event.currentTarget)
              const maxStretch = Number.parseFloat(styles.getPropertyValue("--motion-slider-stretch")) || 1
              const gain = event.currentTarget.clientHeight || 1
              setStretch(Math.min(maxStretch, 1 + Math.abs(event.movementX) / gain))
              const distance = Number.parseFloat(styles.getPropertyValue("--motion-distance-sm")) || 0
              setLag(Math.max(-distance, Math.min(distance, -event.movementX)))
            }}
            onPointerUp={(event) => {
              onPointerUp?.(event)
              setStretch(1)
              setLag(0)
              setHeld(false)
            }}
            onKeyUp={(event) => {
              onKeyUp?.(event)
              setHeld(false)
            }}
            onBlur={(event) => {
              onBlur?.(event)
              setHeld(false)
              setStretch(1)
              setLag(0)
            }}
          >
            <SliderPrimitive.Control ref={rootRef} className="relative flex w-full touch-none items-center">
              <SliderPrimitive.Track
                data-slot="slider-track"
                className="relative h-(--slider-track-height) w-full grow overflow-hidden rounded-full bg-(--slider-track) data-disabled:bg-(--slider-track-disabled)"
              >
                <SliderPrimitive.Indicator data-slot="slider-range" className="h-full bg-(--slider-fill) data-disabled:bg-(--slider-fill-disabled)" />
              </SliderPrimitive.Track>
              {live.map((thumbValue, index) => (
                <SliderPrimitive.Thumb
                  key={index}
                  data-slot="slider-thumb"
                  aria-valuetext={String(thumbValue)}
                  className="hit-target slider-thumb relative block size-(--slider-thumb-size) rounded-full border-0 bg-(--slider-thumb) shadow-(--slider-thumb-elevation) outline-none focus-visible:shadow-(--focus-ring) data-disabled:shadow-none"
                  style={stretch === 1 ? undefined : { scale: `${stretch} 1` }}
                >
                  <span
                    aria-hidden
                    data-held={held && !merge ? "" : undefined}
                    data-merged={merge ? "" : undefined}
                    className="slider-bubble pointer-events-none absolute bottom-full left-1/2 mb-2 rounded-(--radius-pill) bg-foreground px-2 py-0.5 text-xs text-background shadow-2"
                    style={{ "--bubble-lag": `${lag}px` } as React.CSSProperties}
                  >
                    {thumbValue}
                  </span>
                </SliderPrimitive.Thumb>
              ))}
              {merge ? (
                <span
                  aria-hidden
                  className="pointer-events-none absolute"
                  style={{ left: merge.left, top: merge.top }}
                >
                  <GooLayer className="absolute bottom-full left-1/2 mb-2 -translate-x-1/2 overflow-visible" width="72" height="28" viewBox="0 0 72 28">
                    <circle cx="22" cy="14" r="12" className="fill-foreground" />
                    <circle cx="50" cy="14" r="12" className="fill-foreground" />
                  </GooLayer>
                  <span data-held className="slider-bubble absolute bottom-full left-1/2 mb-2 -translate-x-1/2 rounded-(--radius-pill) bg-foreground px-2 py-0.5 text-xs whitespace-nowrap text-background shadow-2">
                    {live[0]}–{live[1]}
                  </span>
                </span>
              ) : null}
            </SliderPrimitive.Control>
          </SliderPrimitive.Root>
        )
      }
      
      export { Slider }
      

Imports

What the examples on this page import:

Imports
import { Slider } from "@/components/ui/slider"

Anatomy

  1. 1Track · --slider-track-height, --slider-track.
  2. 2Fill · --slider-fill.
  3. 3Thumb · --slider-thumb-size, --slider-thumb, --slider-thumb-elevation.
  4. 4Value bubble · Pops above the thumb while dragging.

Props

PropTypeDefaultDescription
defaultValue / valuenumber[]—One value, or two for a range.
min, max, stepnumber0, 100, 1Range and step.
onValueChange(value: number[]) => void—Called while dragging.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--slider-track-heightvar(--space-1)4pxsame
--slider-trackvar(--surface-container-high)oklch(0.94 0.007 95)oklch(0.27 0 0)
--slider-fillvar(--color-brand)oklch(0.18 0.008 260)oklch(0.98 0 0)
--slider-thumb-sizevar(--size-slider-thumb)18pxsame
--slider-thumbvar(--surface-container-lowest)oklch(1 0 0)oklch(0.14 0 0)
--slider-thumb-elevationvar(--elevation-2)0 1px 1px -0.5px oklch(0.22 0.01 260 / 6%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 6%), 0 6px 6px -3px oklch(0.22 0.01 260 / 6%), 0 12px 12px -6px oklch(0.22 0.01 260 / 6%), 0 24px 24px -12px oklch(0.22 0.01 260 / 6%)0 4px 12px oklch(0 0 0 / 40%), 0 12px 28px oklch(0 0 0 / 35%)
--slider-track-disabledvar(--color-bg-disabled)color-mix(in oklch, var(--color-fg-default) var(--state-disabled-container-mix), transparent)same
--slider-fill-disabledvar(--color-fg-disabled)oklch(0.62 0.01 95)oklch(0.53 0 0)

Motion

TriggerWhat happensTokens
DragThe thumb stretches in the drag direction; the bubble follows.--duration-fast, --ease-out

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Arrow keys step; Page Up/Down jump; Home/End go to the ends.
  • Give each thumb an aria-label.

Usage

Do

  • Use when an approximate value is fine.

Don’t

  • Don't use for exact numbers (use a Text field).

Code

components/ui/slider.tsx
"use client"

import * as React from "react"
import { Slider as SliderPrimitive } from "@base-ui/react/slider"
import { cn } from "cn"
import { GooLayer } from "@/components/motion/goo-layer"

function Slider({
  className,
  defaultValue,
  value,
  min = 0,
  max = 100,
  onValueChange,
  onPointerMove,
  onPointerUp,
  onKeyUp,
  onBlur,
  ...props
}: SliderPrimitive.Root.Props) {
  const _values = Array.isArray(value)
    ? value
    : Array.isArray(defaultValue)
      ? defaultValue
      : [min]
  const rootRef = React.useRef<HTMLDivElement>(null)
  const [live, setLive] = React.useState<readonly number[]>(_values)
  const [held, setHeld] = React.useState(false)
  const [stretch, setStretch] = React.useState(1)
  const [lag, setLag] = React.useState(0)
  const [merge, setMerge] = React.useState<{ left: number; top: number } | null>(null)

  React.useLayoutEffect(() => {
    const root = rootRef.current
    if (!root || live.length < 2) return
    const measure = () => {
      const thumbs = [...root.querySelectorAll<HTMLElement>("[data-slot=slider-thumb]")]
      if (thumbs.length < 2) return
      const first = thumbs[0].getBoundingClientRect()
      const second = thumbs[1].getBoundingClientRect()
      if (first.width === 0 || Math.abs(first.left - second.left) < 1) return
      const rootBox = root.getBoundingClientRect()
      const gap = second.left - first.right
      if (gap > first.width) {
        setMerge(null)
        return
      }
      setMerge({
        left: (first.left + second.right) / 2 - rootBox.left,
        top: first.top - rootBox.top,
      })
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(root)
    return () => observer.disconnect()
  }, [live])

  return (
    <SliderPrimitive.Root
      className={cn("relative w-full py-6", className)}
      data-slot="slider"
      defaultValue={defaultValue}
      value={value}
      min={min}
      max={max}
      {...props}
      onValueChange={(next, eventDetails) => {
        setLive(Array.isArray(next) ? next : [next])
        setHeld(true)
        onValueChange?.(next, eventDetails)
      }}
      onPointerMove={(event) => {
        onPointerMove?.(event)
        if (event.buttons === 0) return
        const styles = getComputedStyle(event.currentTarget)
        const maxStretch = Number.parseFloat(styles.getPropertyValue("--motion-slider-stretch")) || 1
        const gain = event.currentTarget.clientHeight || 1
        setStretch(Math.min(maxStretch, 1 + Math.abs(event.movementX) / gain))
        const distance = Number.parseFloat(styles.getPropertyValue("--motion-distance-sm")) || 0
        setLag(Math.max(-distance, Math.min(distance, -event.movementX)))
      }}
      onPointerUp={(event) => {
        onPointerUp?.(event)
        setStretch(1)
        setLag(0)
        setHeld(false)
      }}
      onKeyUp={(event) => {
        onKeyUp?.(event)
        setHeld(false)
      }}
      onBlur={(event) => {
        onBlur?.(event)
        setHeld(false)
        setStretch(1)
        setLag(0)
      }}
    >
      <SliderPrimitive.Control ref={rootRef} className="relative flex w-full touch-none items-center">
        <SliderPrimitive.Track
          data-slot="slider-track"
          className="relative h-(--slider-track-height) w-full grow overflow-hidden rounded-full bg-(--slider-track) data-disabled:bg-(--slider-track-disabled)"
        >
          <SliderPrimitive.Indicator data-slot="slider-range" className="h-full bg-(--slider-fill) data-disabled:bg-(--slider-fill-disabled)" />
        </SliderPrimitive.Track>
        {live.map((thumbValue, index) => (
          <SliderPrimitive.Thumb
            key={index}
            data-slot="slider-thumb"
            aria-valuetext={String(thumbValue)}
            className="hit-target slider-thumb relative block size-(--slider-thumb-size) rounded-full border-0 bg-(--slider-thumb) shadow-(--slider-thumb-elevation) outline-none focus-visible:shadow-(--focus-ring) data-disabled:shadow-none"
            style={stretch === 1 ? undefined : { scale: `${stretch} 1` }}
          >
            <span
              aria-hidden
              data-held={held && !merge ? "" : undefined}
              data-merged={merge ? "" : undefined}
              className="slider-bubble pointer-events-none absolute bottom-full left-1/2 mb-2 rounded-(--radius-pill) bg-foreground px-2 py-0.5 text-xs text-background shadow-2"
              style={{ "--bubble-lag": `${lag}px` } as React.CSSProperties}
            >
              {thumbValue}
            </span>
          </SliderPrimitive.Thumb>
        ))}
        {merge ? (
          <span
            aria-hidden
            className="pointer-events-none absolute"
            style={{ left: merge.left, top: merge.top }}
          >
            <GooLayer className="absolute bottom-full left-1/2 mb-2 -translate-x-1/2 overflow-visible" width="72" height="28" viewBox="0 0 72 28">
              <circle cx="22" cy="14" r="12" className="fill-foreground" />
              <circle cx="50" cy="14" r="12" className="fill-foreground" />
            </GooLayer>
            <span data-held className="slider-bubble absolute bottom-full left-1/2 mb-2 -translate-x-1/2 rounded-(--radius-pill) bg-foreground px-2 py-0.5 text-xs whitespace-nowrap text-background shadow-2">
              {live[0]}–{live[1]}
            </span>
          </span>
        ) : null}
      </SliderPrimitive.Control>
    </SliderPrimitive.Root>
  )
}

export { Slider }