Theme
Version
GitHub PyPI Discord
On this page

Slider and RangeSlider

Use CSlider to choose one value from a bounded exact-decimal scale. Use CRangeSlider when the user chooses an ordered lower and upper value.

<c-CField>
  <c-fill name="label">Volume</c-fill>
  <c-fill name="default">
    <c-CSlider name="volume" value="40" min="0" max="100" />
  </c-fill>
</c-CField>

<c-CField>
  <c-fill name="label">Price range</c-fill>
  <c-fill name="default">
    <c-CRangeSlider name="price" c-value="(20, 80)" min="0" max="100" />
  </c-fill>
</c-CField>
Choose one value
Show code
from decimal import Decimal
from typing import Any

import citry_ui
from citry import Component, citry
from citry_ui import CSlider

citry.register_library(citry_ui)


class BasicSlider(Component):
    class Kwargs:
        pass

    class Slots:
        pass

    def template_data(self, kwargs: Kwargs, slots: Slots) -> dict[str, Any]:  # noqa: ARG002
        return {
            "python_slider": CSlider(
                value=Decimal("0.5"),
                min=Decimal(0),
                max=Decimal(1),
                step=Decimal("0.1"),
                input_attrs={"aria-label": "Python opacity"},
            )
        }

    template = """
      <section class="slider-example-grid">
        <c-CField>
          <c-fill name="label">Volume</c-fill>
          <c-fill name="description">Use arrow keys for one-percent steps.</c-fill>
          <c-fill name="default"><c-CSlider name="volume" value="40" /></c-fill>
        </c-CField>
        <article><h3>Python composition</h3>{{ python_slider }}</article>
      </section>
    """
    css = """
      :where(.slider-example-grid){display:grid;grid-template-columns:repeat(auto-fit,minmax(16rem,1fr));gap:1.5rem}
      :where(.slider-example-grid article){display:grid;gap:.75rem}:where(.slider-example-grid h3){margin:0}
    """


preview = BasicSlider()
preview  # noqa: B018
Choose a value range
Show code
from citry import Component


class RangeSliderExample(Component):
    template = """
      <c-CField>
        <c-fill name="label">Price range</c-fill>
        <c-fill name="description">Lower and upper values stay at least 10 apart.</c-fill>
        <c-fill name="default">
          <c-CRangeSlider name="price" c-value="(20, 80)" c-min_steps_between_thumbs="10" />
        </c-fill>
      </c-CField>
    """


preview = RangeSliderExample()
preview  # noqa: B018

Choose exact values

Server inputs accept int, Decimal, or a canonical plain-decimal string. Floats and exponent notation are rejected. The difference between min and max must contain a whole number of step intervals, capped at one million. Form submission and callbacks use canonical ASCII strings, so values such as Decimal("0.300") submit as 0.3 without binary-float drift.

large_step controls Page Up and Page Down. It defaults to ten steps. Marks label selected grid positions; they do not add selectable values or alter the step grid.

Use an exact decimal scale
Show code
from decimal import Decimal
from typing import Any

from citry import Component


class ExactDecimalSlider(Component):
    def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:  # noqa: ARG002
        return {
            "value": Decimal("0.30"),
            "marks": {Decimal("0.1"): "Low", Decimal("0.3"): "Target", Decimal("0.5"): "High"},
        }

    template = """
      <c-CField>
        <c-fill name="label">Opacity</c-fill>
        <c-fill name="description">Exact 0.05 steps avoid binary floating-point drift.</c-fill>
        <c-fill name="default">
          <c-CSlider c-value="value" min="0.1" max="0.5" step="0.05" c-marks="marks" show_value="always" />
        </c-fill>
      </c-CField>
    """


preview = ExactDecimalSlider()
preview  # noqa: B018
Label selected values
Show code
from typing import Any

from citry import Component


class SliderMarks(Component):
    def template_data(self, kwargs: Any, slots: Any) -> dict[str, Any]:  # noqa: ARG002
        return {"marks": {0: "Silent", 25: "Quiet", 50: "Medium", 75: "Loud", 100: "Maximum"}}

    template = """
      <c-CField>
        <c-fill name="label">Playback volume</c-fill>
        <c-fill name="default"><c-CSlider value="50" c-marks="marks" show_value="always" /></c-fill>
      </c-CField>
    """


preview = SliderMarks()
preview  # noqa: B018

Pick one value or an interval

CSlider contributes one form entry. CRangeSlider name="price" contributes two ordered entries with the same name. Use lower_name and upper_name together when the server expects distinct field names.

Range thumbs keep their lower and upper identities, remain in the same Tab order, and do not cross, swap, or push each other. min_steps_between_thumbs sets a grid-step gap between them.

Submit Slider values
Show code
from citry import Component


class SliderForm(Component):
    template = """
      <form
        x-data="{result:'Submit to inspect values'}"
        @submit.prevent="result=JSON.stringify(Array.from(new FormData($event.target).entries()))"
        class="slider-example-stack"
      >
        <c-CField>
          <c-fill name="label">Budget</c-fill>
          <c-fill name="default">
            <c-CRangeSlider lower_name="minimum" upper_name="maximum" c-value="(25, 75)" />
          </c-fill>
        </c-CField>
        <div><button type="submit">Submit</button> <button type="reset">Reset</button></div>
        <output x-text="result">Submit to inspect values</output>
      </form>
    """
    css = ":where(.slider-example-stack){display:grid;gap:1rem;max-inline-size:32rem}"


preview = SliderForm()
preview  # noqa: B018

Keyboard and pointer behavior

Arrow Right and Arrow Up add one step; Arrow Left and Arrow Down subtract one. Page Up and Page Down use large_step; Home and End move to the current thumb's allowed bounds. For a range, Tab visits lower then upper. Horizontal pointer geometry mirrors in RTL while keyboard value direction stays stable.

The no-JavaScript fallback is one native range input for CSlider and two clearly labeled native range inputs for CRangeSlider. Once enhanced, the styled thumbs take over interaction while the native controls continue to own form submission and reset.

Use vertical Sliders
Show code
from citry import Component


class VerticalSliders(Component):
    template = """
      <section class="vertical-slider-row">
        <c-CSlider value="30" orientation="vertical" c-input_attrs="{'aria-label':'Level'}" />
        <c-CRangeSlider c-value="(20, 70)" orientation="vertical" lower_label="Floor" upper_label="Ceiling" />
      </section>
    """
    css = ":where(.vertical-slider-row){display:flex;gap:3rem;min-block-size:14rem;align-items:center}"


preview = VerticalSliders()
preview  # noqa: B018

Controlled values and callbacks

Omitting client value leaves the component uncontrolled. Supplying it through $c-props makes every interaction a request: the thumb moves only after the owner returns the requested value. onValueChange fires during each accepted pointer or keyboard step. onValueChangeEnd fires once at the end of a pointer gesture and once after a keyboard request.

<div x-data="{ price: ['20', '80'] }">
  <c-CRangeSlider
    c-value="(20, 80)"
    $c-props="{
      value: price,
      onValueChange: (next) => price = next,
    }"
  />
</div>
Control Slider values
Show code
from citry import Component


class ControlledRangeSlider(Component):
    template = """
      <section x-data="{range:['20','80']}" class="slider-example-stack">
        <c-CRangeSlider
          c-value="(20, 80)"
          $c-props="{value:range,onValueChange:(next)=>range=next}"
        />
        <output x-text="`Selected ${range[0]} through ${range[1]}`">Selected 20 through 80</output>
      </section>
    """
    css = ":where(.slider-example-stack){display:grid;gap:1rem;max-inline-size:32rem}"


preview = ControlledRangeSlider()
preview  # noqa: B018

Labels, fields, and localization

Wrap either component in CField for its visible label, description, error, disabled, readonly, and invalid state. A standalone CSlider needs an accessible name through input_attrs. CRangeSlider combines the Field label with localized β€œLower value” and β€œUpper value” labels; override those strings with lower_label and upper_label when the application needs domain-specific names.

Displayed values and aria-valuetext use the number.citry-ui-slider profile. Under a client-enabled c-i18n provider, thumb labels and formatted values update after a browser-side locale switch. Canonical form values never change.

Format localized Slider values
Show code
from citry import Component


class LocalizedSlider(Component):
    template = """
      <section class="slider-example-stack">
        <p>Inside a client-enabled <code>&lt;c-i18n&gt;</code>, labels and formatted values switch locale in place.</p>
        <c-CRangeSlider c-value="('1234.5', '5678.5')" min="0" max="10000" step="0.5" show_value="always" />
        <p>Canonical Form values remain <code>1234.5</code> and <code>5678.5</code>.</p>
      </section>
    """
    css = ":where(.slider-example-stack){display:grid;gap:1rem;max-inline-size:36rem}"


preview = LocalizedSlider()
preview  # noqa: B018

State and customization

readonly preserves a submitted value and focusable slider semantics while blocking mutation. disabled removes interaction and form participation. Choose solid or subtle, three sizes, horizontal or vertical orientation, and never, interaction, or always value bubbles. Use the documented CSS variables and part selectors for styling; attrs and input-attribute mappings cannot replace state, form, identity, or accessibility attributes owned by the component.

Compare Slider states
Show code
from citry import Component


class SliderStates(Component):
    template = """
      <section class="slider-state-grid">
        <c-CSlider value="30" variant="solid" size="sm" c-input_attrs="{'aria-label':'Small solid'}" />
        <c-CSlider value="50" variant="subtle" show_value="always" c-input_attrs="{'aria-label':'Subtle'}" />
        <c-CSlider value="70" size="lg" readonly c-input_attrs="{'aria-label':'Readonly'}" />
        <c-CSlider value="90" disabled invalid c-input_attrs="{'aria-label':'Disabled invalid'}" />
      </section>
    """
    css = ":where(.slider-state-grid){display:grid;gap:1.5rem;max-inline-size:36rem}"


preview = SliderStates()
preview  # noqa: B018

API reference

Inputs

CSlider server inputs

Server inputs are passed in a template through <c-CSlider ... /> or in Python through CSlider(...).

InputTypeDefaultEffect
valueCSliderExact | None (CSliderExact)NoneSets the initial exact value; None uses min.
namestr | NoneNoneNames the progressive native Form entry.
formstr | NoneNoneAssociates the Form entry with an external Form ID.
idstr | NonegeneratedSets the public native input ID and enhanced label target.
minCSliderExact (CSliderExact)0Sets the inclusive exact minimum and step-grid origin.
maxCSliderExact (CSliderExact)100Sets the inclusive exact maximum.
stepCSliderExact (CSliderExact)1Sets the positive exact grid interval.
large_stepCSliderExact | None (CSliderExact)Ten steps.Sets the positive whole-step Page Up and Page Down interval.
disabledbool | NoneNoneBlocks focus mutation and Form participation outside Field.
readonlybool | NoneNonePreserves focus and submission while blocking mutation outside Field.
invalidbool | NoneNoneReflects application invalid state outside Field.
orientation"horizontal" | "vertical" (CSliderOrientation)"horizontal"Selects track orientation.
variant"solid" | "subtle" (CSliderVariant)"solid"Selects visual treatment.
size"sm" | "md" | "lg" (CSliderSize)"md"Selects track and thumb sizing.
show_value"never" | "interaction" | "always" (CSliderShowValue)"interaction"Controls localized value bubbles.
show_marksbool | NoneTrue when marks exist.Shows or hides mark dots and labels.
marksMapping[CSliderExact, str] | Sequence[CSliderExact] | NoneNoneAdds up to 101 bounded step-grid marks.
formatstr"citry-ui-slider"Selects the named i18n number format profile for visible and accessible values.
class_CClassValue | None (CClassValue)NoneAdds classes to the documented root and merges with attrs.
styleCStyleValue | None (CStyleValue)NoneAdds styles to the documented root and merges with attrs.
attrsMapping[str, object] | NoneNoneAdds copied allowed root attributes without replacing owned state or identity.
input_attrsMapping[str, object] | NoneNoneAdds copied allowed native-input attributes including standalone accessible naming.

CRangeSlider server inputs

Server inputs are passed in a template through <c-CRangeSlider ... /> or in Python through CRangeSlider(...).

InputTypeDefaultEffect
valuetuple[CSliderExact, CSliderExact] | None (CSliderExact)(min, max)Sets the initial ordered lower and upper exact values.
namestr | NoneNoneNames both ordered Form entries when separate names are omitted.
lower_namestr | NoneNoneNames the lower Form entry when supplied together with upper_name.
upper_namestr | NoneNoneNames the upper Form entry when supplied together with lower_name.
formstr | NoneNoneAssociates both Form entries with an external Form ID.
idstr | NonegeneratedSets the lower native input ID and bases the generated upper and root IDs.
minCSliderExact (CSliderExact)0Sets the inclusive exact minimum and step-grid origin.
maxCSliderExact (CSliderExact)100Sets the inclusive exact maximum.
stepCSliderExact (CSliderExact)1Sets the positive exact grid interval.
large_stepCSliderExact | None (CSliderExact)Ten steps.Sets the positive whole-step Page Up and Page Down interval.
min_steps_between_thumbsint0Keeps this many grid intervals between fixed lower and upper thumbs.
disabledbool | NoneNoneBlocks focus mutation and Form participation outside Field.
readonlybool | NoneNonePreserves focus and ordered submission while blocking mutation outside Field.
invalidbool | NoneNoneReflects application invalid state outside Field.
orientation"horizontal" | "vertical" (CSliderOrientation)"horizontal"Selects track orientation.
variant"solid" | "subtle" (CSliderVariant)"solid"Selects visual treatment.
size"sm" | "md" | "lg" (CSliderSize)"md"Selects track and thumb sizing.
show_value"never" | "interaction" | "always" (CSliderShowValue)"interaction"Controls both localized value bubbles.
show_marksbool | NoneTrue when marks exist.Shows or hides mark dots and labels.
marksMapping[CSliderExact, str] | Sequence[CSliderExact] | NoneNoneAdds up to 101 bounded step-grid marks.
formatstr"citry-ui-slider"Selects the named i18n number format profile for both values.
lower_labelstr"Lower value"Overrides the catalog-backed lower-thumb accessible name.
upper_labelstr"Upper value"Overrides the catalog-backed upper-thumb accessible name.
class_CClassValue | None (CClassValue)NoneAdds classes to the documented root and merges with attrs.
styleCStyleValue | None (CStyleValue)NoneAdds styles to the documented root and merges with attrs.
attrsMapping[str, object] | NoneNoneAdds copied allowed root attributes without replacing owned state or identity.
lower_input_attrsMapping[str, object] | NoneNoneAdds copied allowed attributes to the lower native input.
upper_input_attrsMapping[str, object] | NoneNoneAdds copied allowed attributes to the upper native input.

CSlider client inputs

Client inputs are passed in the browser through the $c-props="{ ... }" attribute on <c-CSlider />.

InputTypeOmitted behaviorEffect
valuecanonical decimal stringReleases control to the last uncontrolled value.Controls the exact value while supplied.
mincanonical decimal stringUses the server value.Replaces the minimum when the resulting grid is valid.
maxcanonical decimal stringUses the server value.Replaces the maximum when the resulting grid is valid.
steppositive canonical decimal stringUses the server value.Replaces the grid interval when min and max contain whole steps.
largeSteppositive canonical decimal stringUses the server value.Replaces the Page Up and Page Down interval.
disabledbooleanUses server or owner state.Controls mutation and Form participation.
readonlybooleanUses server or owner state.Controls focusable nonmutable state.
invalidbooleanUses server or Field state.Controls application invalid state.
orientationCSliderOrientation (CSliderOrientation)Uses the server value.Controls track orientation.
variantCSliderVariant (CSliderVariant)Uses the server value.Controls visual treatment.
sizeCSliderSize (CSliderSize)Uses the server value.Controls coordinated sizing.
showValueCSliderShowValue (CSliderShowValue)Uses the server value.Controls value-bubble visibility.
formatstringUses the server profile.Controls locale-aware visible and accessible value formatting.
onValueChangefunctionNo live value callback.Receives each user value request.
onValueChangeEndfunctionNo completed-interaction callback.Receives each keyboard request and completed pointer gesture.

CRangeSlider client inputs

Client inputs are passed in the browser through the $c-props="{ ... }" attribute on <c-CRangeSlider />.

InputTypeOmitted behaviorEffect
value[canonical decimal string, canonical decimal string]Releases control to the last uncontrolled pair.Controls the ordered exact pair while supplied.
mincanonical decimal stringUses the server value.Replaces the minimum when the resulting grid is valid.
maxcanonical decimal stringUses the server value.Replaces the maximum when the resulting grid is valid.
steppositive canonical decimal stringUses the server value.Replaces the grid interval when min and max contain whole steps.
largeSteppositive canonical decimal stringUses the server value.Replaces the Page Up and Page Down interval.
minStepsBetweenThumbsnonnegative integerUses the server value.Controls the minimum lower-to-upper grid gap.
disabledbooleanUses server or owner state.Controls mutation and Form participation.
readonlybooleanUses server or owner state.Controls focusable nonmutable state.
invalidbooleanUses server or Field state.Controls application invalid state.
orientationCSliderOrientation (CSliderOrientation)Uses the server value.Controls track orientation.
variantCSliderVariant (CSliderVariant)Uses the server value.Controls visual treatment.
sizeCSliderSize (CSliderSize)Uses the server value.Controls coordinated sizing.
showValueCSliderShowValue (CSliderShowValue)Uses the server value.Controls both value bubbles.
formatstringUses the server profile.Controls locale-aware visible and accessible value formatting.
onValueChangefunctionNo live value callback.Receives each ordered-pair request.
onValueChangeEndfunctionNo completed-interaction callback.Receives each keyboard request and completed pointer gesture.

Slots

-

Events

Component events are callback inputs supplied through $c-props. Native browser events remain available through Alpine @... attributes.

CSlider events

EventSignatureTrigger and timingDetailControlled and cancellation behavior
onValueChange(value: string, detail: CSliderValueChangeDetail) => void (CSliderValueChangeDetail)Each pointer-drag or keyboard value request.{value, previousValue, controlled, source, sourceEvent, phase} (CSliderValueChangeDetail)Uncontrolled state and native Form value update before notification; controlled state is request-only.
onValueChangeEnd(value: string, detail: CSliderValueChangeDetail) => void (CSliderValueChangeDetail)A keyboard request or completed changed pointer gesture.{value, previousValue, controlled, source, sourceEvent, phase} (CSliderValueChangeDetail)Reports the final requested value once per completed interaction.

CRangeSlider events

EventSignatureTrigger and timingDetailControlled and cancellation behavior
onValueChange(value: tuple[str, str], detail: CRangeSliderValueChangeDetail) => void (CRangeSliderValueChangeDetail)Each lower or upper pointer-drag or keyboard pair request.{value, previousValue, controlled, source, sourceEvent, phase, activeThumb} (CRangeSliderValueChangeDetail)Preserves ordered stable thumb identity; controlled state is request-only.
onValueChangeEnd(value: tuple[str, str], detail: CRangeSliderValueChangeDetail) => void (CRangeSliderValueChangeDetail)A keyboard request or completed changed pointer gesture.{value, previousValue, controlled, source, sourceEvent, phase, activeThumb} (CRangeSliderValueChangeDetail)Reports the final requested ordered pair once per completed interaction.

Methods

-

CSS

CSS variables to theme the components. Set them on an ancestor or the component itself.

CSlider CSS variables

Apply these variables to CSlider or one of its ancestors.

VariableTypePurposeDefault
--cui-slider-track-colorcolorUnfilled rail color.Mixed CanvasText.
--cui-slider-fill-colorcolorSelected rail color.AccentColor
--cui-slider-thumb-colorcolorThumb fill.Canvas
--cui-slider-thumb-border-colorcolorThumb outline.AccentColor
--cui-slider-focus-colorcolorKeyboard focus ring.Highlight
--cui-slider-mark-colorcolorMark dots.CanvasText
--cui-slider-value-backgroundcolorValue-bubble background.High-contrast ink.
--cui-slider-value-foregroundcolorValue-bubble text.High-contrast surface.
--cui-slider-track-sizelengthRail thickness.0.375rem
--cui-slider-thumb-sizelengthThumb diameter.1.25rem
--cui-slider-control-sizelengthMinimum interaction block size.2.75rem
--cui-slider-radiuslengthRail and thumb rounding.999px

Attributes

HTML attributes defined on the components that you can refer to for CSS, inspection, and testing. Read-only.

CSlider attributes

AttributeElementTypeMeaning
data-disabledRoot divpresent | absentMirrors effective disabledness.
data-readonlyRoot divpresent | absentMirrors effective readonly state.
data-invalidRoot divpresent | absentMirrors effective invalid state.
data-draggingRoot divpresent | absentMarks an active pointer gesture.
data-orientationRoot divCSliderOrientation (CSliderOrientation)Mirrors track orientation.
data-variantRoot divCSliderVariant (CSliderVariant)Mirrors visual treatment.
data-sizeRoot divCSliderSize (CSliderSize)Mirrors coordinated sizing.
data-show-valueRoot divCSliderShowValue (CSliderShowValue)Mirrors value-bubble policy.

CSlider attributes

AttributeElementTypeMeaning
roleEnhanced thumb Button"slider"Exposes slider interaction semantics.
aria-valuenowEnhanced thumb Buttoncanonical decimalExposes the exact current value.
aria-valuetextEnhanced thumb Buttonlocalized stringExposes the locale-formatted current value.
aria-valueminEnhanced thumb Buttoncanonical decimalExposes the current inclusive lower bound.
aria-valuemaxEnhanced thumb Buttoncanonical decimalExposes the current inclusive upper bound.

Selectors

Selectors for the DOM nodes in the components that you can use for CSS, inspection, and testing.

CSlider selectors

SelectorElementPurpose
[data-citry-ui-part="slider"]CSlider root divState reflections and root customization destination.
[data-citry-ui-part="range-slider"]CRangeSlider root divState reflections and root customization destination.
[data-citry-ui-part="native-input"]Native range inputNo-JavaScript fallback and enhanced Form transport.
[data-citry-ui-part="control"]Enhanced control divPointer interaction surface.
[data-citry-ui-part="track"]Track divPositions fill marks and thumbs.
[data-citry-ui-part="fill"]Fill spanShows the selected value or interval.
[data-citry-ui-part="mark"]Mark spanShows a configured grid position.
[data-citry-ui-part="mark-label"]Mark label spanShows application-owned mark text.
[data-citry-ui-part="thumb"]Enhanced slider ButtonKeyboard focus target and draggable value owner.
[data-citry-ui-part="value"]Value spanShows the locale-formatted current value.

Interfaces

Aliases and data shapes referenced above.

Input type aliases

InterfaceDefinition
CSliderExactint | Decimal | str
CSliderOrientationLiteral["horizontal", "vertical"]
CSliderVariantLiteral["solid", "subtle"]
CSliderSizeLiteral["sm", "md", "lg"]
CSliderShowValueLiteral["never", "interaction", "always"]
CSliderChangeSourceLiteral["pointer", "keyboard", "reset"]
CSliderChangePhaseLiteral["change", "end"]
CRangeSliderThumbLiteral["lower", "upper"]
CClassValuestr | Mapping[str, bool] | Sequence[CClassValue]
CStyleValuestr | Mapping[str, object] | Sequence[CStyleValue]

CSliderValueChangeDetail

FieldTypeDefaultMeaning
valuecanonical decimal string-Requested exact value.
previousValuecanonical decimal string-Effective exact value before the interaction.
controlledboolean-Whether client value owns state.
sourceCSliderChangeSource (CSliderChangeSource)-Pointer keyboard or reset cause.
sourceEventobject | null-Native interaction event when one exists.
phaseCSliderChangePhase (CSliderChangePhase)-Live change or completed interaction.

CRangeSliderValueChangeDetail

FieldTypeDefaultMeaning
value[canonical decimal string, canonical decimal string]-Requested ordered exact pair.
previousValue[canonical decimal string, canonical decimal string]-Effective ordered pair before the interaction.
controlledboolean-Whether client value owns state.
sourceCSliderChangeSource (CSliderChangeSource)-Pointer keyboard or reset cause.
sourceEventobject | null-Native interaction event when one exists.
phaseCSliderChangePhase (CSliderChangePhase)-Live change or completed interaction.
activeThumbCRangeSliderThumb (CRangeSliderThumb)-Stable lower or upper thumb that requested the change.

Translation keys

Catalog keys used by this family. An explicit component input or slot listed in Override takes precedence over the catalog for that instance.

CRangeSlider translation keys

KeyPurposeVariablesOverrideBrowser updates
citry-ui-range-slider-lowerDistinguishes the lower thumb and native fallback input.Nonelower_label$c-tr updates the stable hidden label; both controls reference it.
citry-ui-range-slider-upperDistinguishes the upper thumb and native fallback input.Noneupper_label$c-tr updates the stable hidden label; both controls reference it.