Slider
The Slider component allows users to select a value or range from a specified minimum and maximum. It’s perfect for adjusting settings like volume, brightness, or filter values with an accessible and interactive control.
Usage
<script>
import { Slider } from "$lib/components/ui/slider";
let value = [50];
</script>
<Slider bind:value={value} />
Examples
Basic Slider
A simple slider with a single value.
Range Slider
A slider that allows selecting a range with two handles.
With Custom Steps
A slider with custom step increments.
With Min and Max
A slider with custom minimum and maximum values.
Temperature (15°C - 30°C)
With Form Label
A slider with a form label for accessibility.
Adjust the volume level (currently at 75%).
Disabled
A disabled slider.
Custom Styling
A slider with custom styling.
API Reference
Slider
Property | Type | Default | Description |
---|---|---|---|
value | number[] | [] | An array of values for the slider. For a single thumb slider, use a one-element array. For a range slider, use a two-element array. |
min | number | 0 | The minimum value for the slider. |
max | number | 100 | The maximum value for the slider. |
step | number | 1 | The step increment for the slider. |
disabled | boolean | false | Whether the slider is disabled. |
orientation | "horizontal" \| "vertical" | "horizontal" | The orientation of the slider. |
dir | "ltr" \| "rtl" | "ltr" | The reading direction of the slider. |
inverted | boolean | false | Whether the slider’s values are inverted. |
class | string | - | Additional CSS classes to add to the slider. |
onValueChange | (value: number[]) => void | - | Callback called when the value changes. |
onValueCommit | (value: number[]) => void | - | Callback called when the user has finished moving the slider. |
Implementation
The Slider component is built on top of bits-ui primitives. Here’s how the component is implemented:
<SliderPrimitive.Root
bind:ref
bind:value={value as never}
class={cn("relative flex w-full touch-none select-none items-center", className)}
{...restProps}
>
{#snippet children({ thumbs })}
<span class="bg-primary/20 relative h-1.5 w-full grow overflow-hidden rounded-full">
<SliderPrimitive.Range class="bg-primary absolute h-full" />
</span>
{#each thumbs as thumb}
<SliderPrimitive.Thumb
index={thumb}
class="border-primary/50 bg-background focus-visible:ring-ring block size-4 rounded-full border shadow transition-colors focus-visible:outline-none focus-visible:ring-1 disabled:pointer-events-none disabled:opacity-50"
/>
{/each}
{/snippet}
</SliderPrimitive.Root>
The component uses CSS variables to calculate the position of thumbs and tracks. It’s built with accessibility in mind, supporting keyboard navigation, ARIA attributes, and proper focus management.