---
title: Slider for Astro
description: "Astro range controls with data-slot pointer and keyboard input."
seo:
    title: Slider for Astro | Shadcn & Tailwind CSS
related:
    - /components/input
    - /components/progress
sidebar:
    label: "Slider"
---

```astro
---
import { Slider, SliderValue } from "@/components/ui/slider"
---

<Slider defaultValue={33} aria-label="Value" class="w-full max-w-md">
  <SliderValue />
</Slider>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/slider
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/core @data-slot/slider
```

#### src/components/ui/slider/index.ts

```ts
export { default as Slider } from './slider.astro'
export { default as SliderValue } from './slider-value.astro'
export { createSliderForm } from './slider-form.ts'
export { createSliderValue } from './slider-value.ts'
export type { SliderProps, SliderValueProps } from './types.ts'
```

#### src/components/ui/slider/slider.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { SliderProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & SliderProps

const {
  class: className,
  defaultValue,
  min,
  max,
  step,
  largeStep,
  orientation = "horizontal",
  thumbAlignment = "edge",
  disabled,
  format,
  locale,
  name,
  form,
  ...props
} = Astro.props

const serializedDefaultValue = Array.isArray(defaultValue)
  ? [...defaultValue].sort((a, b) => a - b).join(",")
  : defaultValue
const formMin = Math.min(min ?? 0, max ?? 100)
const formMax = Math.max(min ?? 0, max ?? 100)
const formValues = name
  ? String(serializedDefaultValue ?? formMin).split(",")
  : []
const thumbCount = String(serializedDefaultValue ?? "").includes(",") ? 2 : 1
---

<div
  data-slot="slider"
  data-slider-format={
    format || locale ? JSON.stringify({ locale, format }) : undefined
  }
  data-default-value={serializedDefaultValue}
  data-min={min}
  data-max={max}
  data-step={step}
  data-large-step={largeStep}
  data-orientation={orientation}
  data-thumb-alignment={thumbAlignment}
  data-disabled={disabled ? "true" : undefined}
  class={cn(
    "data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full",
    Astro.slots.has("default") && "flex flex-col gap-3",
    className,
  )}
  {...props}
>
  {formValues.map((value) => (
    <input
      data-slot="slider-form-input"
      type="range"
      hidden
      name={name}
      form={form}
      min={formMin}
      max={formMax}
      step={step && step > 0 ? step : 1}
      value={value}
      disabled={disabled}
    />
  ))}
  <slot />
  <div
    data-slot="slider-control"
    data-orientation={orientation}
    data-disabled={disabled ? "true" : undefined}
    class="flex touch-none select-none data-disabled:pointer-events-none data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=horizontal]:w-full data-[orientation=horizontal]:min-w-44 data-[orientation=vertical]:flex-col data-disabled:opacity-64 relative items-center"
  >
    <div data-slot="slider-track" class="relative grow select-none before:absolute before:rounded-full before:bg-input data-[orientation=horizontal]:h-1 data-[orientation=vertical]:h-full data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-1 data-[orientation=horizontal]:before:inset-x-0.5 data-[orientation=vertical]:before:inset-x-0 data-[orientation=horizontal]:before:inset-y-0 data-[orientation=vertical]:before:inset-y-0.5">
      <div data-slot="slider-range" class="select-none rounded-full bg-primary data-[orientation=horizontal]:ms-0.5 data-[orientation=vertical]:mb-0.5 data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"></div>
    </div>
    {Array.from({ length: thumbCount }).map(() => (
      <div
        data-slot="slider-thumb"
        class="block size-5 shrink-0 select-none rounded-full border border-input bg-white not-dark:bg-clip-padding shadow-xs/5 outline-none transition-[box-shadow,scale] before:absolute before:inset-0 before:rounded-full before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-[3px] focus-visible:ring-ring/24 data-dragging:scale-120 sm:size-4 dark:border-background dark:focus-visible:ring-ring/48 [:focus-visible,[data-dragging]]:shadow-none"
        aria-label={thumbCount === 1 ? props["aria-label"] : undefined}
        aria-labelledby={
          thumbCount === 1 ? props["aria-labelledby"] : undefined
        }
        aria-describedby={props["aria-describedby"]}
      />
    ))}
  </div>
</div>

<script>
  import { create } from "@data-slot/slider"
  import type { SliderController } from "@data-slot/slider"
  import { bindSliderForms } from "./slider-form.ts"
  import { bindSliderValues } from "./slider-value.ts"
  // Destroy bindings before a view transition so the next page-load binds once.
  const controllers: Pick<SliderController, "destroy">[] = []
  const initialize = () => {
    controllers.push(...create(), ...bindSliderForms(), ...bindSliderValues())
  }
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/slider/slider-form.ts

```ts
import {
    clearRootBinding,
    getParts,
    getRootBinding,
    getRoots,
    hasRootBinding,
    observeFormReset,
    setRootBinding,
} from '@data-slot/core'
import type { SliderController } from '@data-slot/slider'

import type { SliderEventDetail } from './types.ts'

const binding = '@gnostic/slider-form'

/** Keep native form fields in sync with an initialized slider. */
export function createSliderForm(root: HTMLElement) {
    const existing = getRootBinding<{ destroy(): void }>(root, binding)
    if (existing) return existing
    const inputs = getParts<HTMLInputElement>(root, 'slider-form-input')
    const first = inputs[0]
    const slider = getRootBinding<SliderController>(root, '@data-slot/slider')
    if (!first || !slider) return

    const values = (value: SliderController['value']) =>
        Array.isArray(value) ? value : [value]
    const fallback = inputs.map((input) => ({
        step: input.step,
        value: input.defaultValue,
    }))
    const initial = values(slider.value)
    for (const [index, input] of inputs.entries()) {
        // The slider applies its step before it emits a value. Keep its exact endpoints.
        input.step = 'any'
        input.defaultValue = String(initial[index])
        input.value = input.defaultValue
    }
    const syncInputs = () => {
        const next = values(slider.value)
        inputs.forEach((input, index) => {
            input.value = String(next[index])
        })
    }
    const onSliderChange = (event: CustomEvent<SliderEventDetail>) => {
        if (event.target === root) syncInputs()
    }
    const syncSlider = () => {
        const second = inputs[1]
        slider.setValue(
            second
                ? [first.valueAsNumber, second.valueAsNumber]
                : first.valueAsNumber,
        )
        syncInputs()
    }
    const reset = observeFormReset({
        root,
        getForm: () => first.form,
        onReset: syncSlider,
    })
    const events = new AbortController()
    root.addEventListener('slider:change', onSliderChange, {
        signal: events.signal,
    })
    for (const input of inputs) {
        input.addEventListener('input', syncSlider, { signal: events.signal })
        input.addEventListener('change', syncSlider, { signal: events.signal })
    }
    const controller = {
        destroy() {
            if (events.signal.aborted) return
            events.abort()
            reset.destroy()
            inputs.forEach((input, index) => {
                input.step = fallback[index]!.step
                input.defaultValue = fallback[index]!.value
                input.value = input.defaultValue
            })
            clearRootBinding(root, binding, controller)
        },
    }
    return setRootBinding(root, binding, controller)
}

export function bindSliderForms(scope: ParentNode = document) {
    return getRoots<HTMLElement>(scope, 'slider')
        .filter((root) => !hasRootBinding(root, binding))
        .flatMap((root) => createSliderForm(root) ?? [])
}
```

#### src/components/ui/slider/slider-value.astro

```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { SliderValueProps } from "./types.ts"

type Props<Tag extends HTMLTag = "output"> = Polymorphic<{ as: Tag }> &
  SliderValueProps
const { as: Tag = "output", class: className, sliderId, ...props } = Astro.props
---

<Tag
  data-slot="slider-value"
  data-slider-id={sliderId}
  aria-live="off"
  class={cn("text-sm tabular-nums text-foreground", className)}
  {...props}
>
  <slot />
</Tag>
```

#### src/components/ui/slider/slider-value.ts

```ts
import {
    clearRootBinding,
    ensureId,
    getParts,
    getRootBinding,
    getRoots,
    hasRootBinding,
    setRootBinding,
} from '@data-slot/core'
import type { SliderController } from '@data-slot/slider'

import type { SliderEventDetail, SliderProps } from './types.ts'

const binding = '@gnostic/slider-value'

// Create once per binding. Slider changes can fire on every pointer move.
function numberFormatter(root: HTMLElement) {
    if (!root.dataset.sliderFormat) return
    const { locale, format } = JSON.parse(root.dataset.sliderFormat) as Pick<
        SliderProps,
        'locale' | 'format'
    >
    return new Intl.NumberFormat(locale, format)
}

function bindThumbFormat(root: HTMLElement) {
    const key = '@gnostic/slider-format'
    if (hasRootBinding(root, key)) return
    const slider = getRootBinding<SliderController>(root, '@data-slot/slider')
    const formatter = numberFormatter(root)
    if (!slider || !formatter) return
    const thumbs = getParts(root, 'slider-thumb')
    const previous = thumbs.map((thumb) => thumb.getAttribute('aria-valuetext'))
    const render = (value: SliderController['value']) => {
        const values = Array.isArray(value) ? value : [value]
        thumbs.forEach((thumb, index) =>
            thumb.setAttribute(
                'aria-valuetext',
                formatter.format(values[index]),
            ),
        )
    }
    const update = (event: CustomEvent<SliderEventDetail>) => {
        if (event.target === root) render(event.detail.value)
    }
    render(slider.value)
    root.addEventListener('slider:change', update)
    const controller = {
        destroy() {
            if (getRootBinding(root, key) !== controller) return
            root.removeEventListener('slider:change', update)
            thumbs.forEach((thumb, index) => {
                const text = previous[index]
                if (text == null) thumb.removeAttribute('aria-valuetext')
                else thumb.setAttribute('aria-valuetext', text)
            })
            clearRootBinding(root, key, controller)
        },
    }
    return setRootBinding(root, key, controller)
}

/** Connect a readout to an initialized data-slot slider. */
export function createSliderValue(output: HTMLElement) {
    const existing = getRootBinding<{ destroy(): void }>(output, binding)
    if (existing) return existing
    const id = output.dataset.sliderId
    const root =
        id === undefined
            ? output.closest<HTMLElement>('[data-slot="slider"]')
            : output.ownerDocument.getElementById(id)
    if (!root) return
    const slider = getRootBinding<SliderController>(root, '@data-slot/slider')
    if (!slider) return

    const linkFields =
        output instanceof HTMLOutputElement && !output.hasAttribute('for')
    if (linkFields) {
        const fields = getParts(root, 'slider-form-input')
        const sources = fields.length ? fields : getParts(root, 'slider-thumb')
        output.htmlFor.value = sources
            .map((source) => ensureId(source, 'slider-input'))
            .join(' ')
    }
    const format = numberFormatter(root)?.format ?? String
    const fallback = Array.from(output.childNodes)
    const render = (value: SliderController['value']) => {
        output.textContent = Array.isArray(value)
            ? value.map(format).join(' – ')
            : format(value)
    }
    const update = (event: CustomEvent<SliderEventDetail>) => {
        if (event.target === root) render(event.detail.value)
    }
    render(slider.value)
    root.addEventListener('slider:change', update)
    const controller = {
        destroy() {
            if (getRootBinding(output, binding) !== controller) return
            root.removeEventListener('slider:change', update)
            if (linkFields) output.removeAttribute('for')
            output.replaceChildren(...fallback)
            clearRootBinding(output, binding, controller)
        },
    }
    return setRootBinding(output, binding, controller)
}

export function bindSliderValues(scope: ParentNode = document) {
    const formatted = getRoots<HTMLElement>(scope, 'slider')
        .filter((root) => root.hasAttribute('data-slider-format'))
        .flatMap((root) => bindThumbFormat(root) ?? [])
    const outputs = getRoots<HTMLElement>(scope, 'slider-value')
        .filter((output) => !hasRootBinding(output, binding))
        .flatMap((output) => createSliderValue(output) ?? [])
    return [...formatted, ...outputs]
}
```

#### src/components/ui/slider/types.ts

```ts
import type { SliderOptions } from '@data-slot/slider'

/**
 * Slider configuration rendered as data attributes.
 */
export type SliderProps = Pick<
    SliderOptions,
    | 'defaultValue'
    | 'min'
    | 'max'
    | 'step'
    | 'largeStep'
    | 'orientation'
    | 'thumbAlignment'
    | 'disabled'
> & {
    /** Number format for the readout and accessible thumb values. */
    format?: Intl.NumberFormatOptions
    /** Language tag or ordered list of tags for number formatting. Defaults to the browser locale. */
    locale?: string | string[]
    /** Name submitted with each thumb value. Omit to exclude the slider from form data. */
    name?: string
    /** ID of the form that owns the slider. Defaults to the enclosing form. */
    form?: string
}

/** Display the current value of a slider. */
export interface SliderValueProps {
    /** ID of the slider when the readout is outside it. Defaults to the nearest parent slider. */
    sliderId?: string
}

export interface SliderEventDetail {
    value: number | [number, number]
}

declare global {
    interface HTMLElementEventMap {
        'slider:change': CustomEvent<SliderEventDetail>
        'slider:commit': CustomEvent<SliderEventDetail>
        'slider:set': CustomEvent<SliderEventDetail>
    }
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
import { Slider, SliderValue } from "@/components/ui/slider"
---
```

```astro
<Slider defaultValue={33} aria-label="Volume">
  <SliderValue />
</Slider>
```

Put `SliderValue` inside `Slider` to display its current value. It finds the nearest parent slider, even through a layout wrapper. The readout shows the initial value when the slider initializes and updates with pointer, keyboard, and programmatic changes. A range displays both values, such as `25 – 75`.

Children appear above the drag control. To place a readout elsewhere, give the slider a unique `id` and pass that ID to `SliderValue` as `sliderId`.

## Examples

### Field

Set `format` on the slider to apply the same number format to each readout and thumb. For a volume slider from 0 to 100, this displays `40%` for a value of `40`.

```astro
<Slider name="volume" defaultValue={40} aria-label="Volume" format={{ style: "unit", unit: "percent" }}>
  <SliderValue />
</Slider>
```

For a scale from 0 to 1, use `format={{ style: "percent" }}` to display `0.4` as `40%`. Set `locale` to choose a language for the formatted text. Forms submit the numeric value as a string.

```astro
---
import { Slider, SliderValue } from "@/components/ui/slider"
import { Field, FieldDescription, FieldTitle } from "@/components/ui/field"
---

<form class="w-full max-w-md">
  <Field>
    <Slider
      name="volume"
      defaultValue={40}
      format={{ style: "unit", unit: "percent" }}
      aria-label="Volume"
    >
      <div class="flex items-center justify-between">
        <FieldTitle>Volume</FieldTitle>
        <SliderValue />
      </div>
    </Slider>
    <FieldDescription>Adjust the audio volume.</FieldDescription>
  </Field>
</form>
```

Set `name="volume"` to submit the current value with a form. Read it with `new FormData(form).get("volume")`. Set `form` to a form ID if the slider is outside that form. Disabled sliders are excluded from submission. A form reset restores the initial setting and the readout.

### Range

Use an array with two values for a range slider. Both thumbs use the same field name. With `name="price"`, `new FormData(form).getAll("price")` returns the lower and upper values as strings.

```astro
---
import { Slider, SliderValue } from "@/components/ui/slider"
---

<form class="w-full max-w-md">
  <Slider
    name="price"
    defaultValue={[25, 75]}
    max={100}
    step={1}
    class="w-full max-w-md"
  >
    <SliderValue />
  </Slider>
</form>
```

### Vertical

Use `orientation="vertical"` for a vertical slider.

```astro
---
import { Slider } from "@/components/ui/slider"
---

<div class="flex h-48 items-center">
  <Slider
    orientation="vertical"
    defaultValue={60}
    max={100}
    step={5}
    thumbAlignment="edge"
    class="h-full"
  />
</div>
```

### Disabled

Use the `disabled` prop to disable the slider.

```astro
---
import { Slider } from "@/components/ui/slider"
---

<Slider
  defaultValue={50}
  disabled
  thumbAlignment="edge"
  class="w-full max-w-md"
/>
```

## API Reference

### SliderProps

<AutoTypeTable path="../../packages/ui/src/components/ui/slider/types.ts" name="SliderProps" />

### SliderValueProps

<AutoTypeTable path="../../packages/ui/src/components/ui/slider/types.ts" name="SliderValueProps" />

`SliderValue` renders an `<output>` by default. Use `as` to change the element. The default slot supplies fallback content. The first render of the live value replaces it. Use the slider’s `format` prop for units, currency, or decimal precision.

See the [data-slot docs](https://github.com/bejamas/data-slot/blob/main/packages/slider/README.md) for more information on interactivity.

### Events

Dispatch these events on the slider root. The root emits the outbound events.

#### Outbound events

| Event           | Detail                                  |
| --------------- | --------------------------------------- |
| `slider:change` | `{ value: number \| [number, number] }` |
| `slider:commit` | `{ value: number \| [number, number] }` |

#### Inbound events

| Event        | Detail                                  |
| ------------ | --------------------------------------- |
| `slider:set` | `{ value: number \| [number, number] }` |

Read the [installed source](/ui/r/slider.json) for the complete prop types.

## When to use Slider

Use Slider when an approximate position within a range is easier to choose than a typed value. Set bounds and step for the real data. Keep a visible label and, where useful, a readable current value.

## Keyboard and behavior

The data-slot controller moves the thumb and handles keyboard input. Test endpoints, arrow keys, and disabled behavior. For values that require precision, provide another way to enter or confirm the exact number.

## Theme and layout

Track, range, and thumb use input and primary tokens. Check focus contrast and touch use at narrow widths. Value persistence and any effect on application data remain your responsibility.
