Components

Switch

A switch built on the native checkbox input, with a sliding knob, on, focus, disabled, read-only, and invalid states, light, dark, and neutral track colors, and three sizes through the recipe system.

Overview

The Switch is a binary form control that lets users switch an option on or off, rendered as a sliding switch. It is composed of two recipe parts:

  • useSwitchRecipe() — the label wrapper that owns the inline layout (gap, alignment), label typography, and the switch's hit area, and dims itself when the field is disabled.
  • useSwitchFieldRecipe() — the native styled input rendered as a pill track with a sliding knob, plus the on (checked), focus, disabled, read-only, and invalid states.

The field is the real native <input type="checkbox" role="switch">, so every state is driven by the input itself: :checked recolors the track to @color.primary and moves the knob to the inline end, :focus-visible shows a @color.focus ring, [aria-invalid="true"] draws an error border, [aria-readonly="true"] a dashed one, and :disabled dims it. The color axis sets the off track surface (light, dark, neutral) and the on-track fill stays @color.primary across all three.

The Switch recipes integrate directly with the default design tokens preset and generate type-safe utility classes at build time with zero runtime CSS.

Why use the Switch recipe?

The Switch recipe helps you:

  • Ship faster with sensible defaults: Get 3 surface colors and 3 sizes out of the box with a single set of composable calls.
  • Build on the native input: States ride on native pseudo-classes (:checked, :disabled, :focus-visible), so the control stays keyboard-accessible and form-associated with zero runtime JavaScript.
  • Maintain consistency: The on-track fill, knob, focus ring, and dark-mode surfaces follow the same design rules everywhere.
  • Customize without forking: Override base styles, default variants, or filter out options you don't need — all through the options API.
  • Stay type-safe: Full TypeScript support means your editor catches invalid color or size values at compile time.
  • Integrate with your tokens: Every value references the design tokens preset, so theme changes propagate automatically.

Usage

Register the recipes

Add the Switch recipes to a local Styleframe instance. The global styleframe.config.ts provides design tokens and utilities, while the component-level file registers the recipes themselves:

src/components/switch.styleframe.ts
import { styleframe } from 'virtual:styleframe';
import { useSwitchRecipe, useSwitchFieldRecipe } from '@styleframe/theme';

const s = styleframe();

const switchRecipe = useSwitchRecipe(s);
const switchField = useSwitchFieldRecipe(s);

export default s;

Build the component

Put the switchRecipe wrapper on the <label> and the switchField switch on a native <input type="checkbox" role="switch">. The role="switch" tells assistive technology to announce the control as on/off rather than checked/unchecked:

src/components/Switch.tsx
import { switchRecipe, switchField } from "virtual:styleframe";

interface SwitchProps {
    color?: "light" | "dark" | "neutral";
    size?: "sm" | "md" | "lg";
    checked?: boolean;
    disabled?: boolean;
    label?: string;
}

export function Switch({
    color = "neutral",
    size = "md",
    checked = false,
    disabled = false,
    label,
}: SwitchProps) {
    return (
        <label className={switchRecipe({ size })}>
            <input
                type="checkbox"
                role="switch"
                className={switchField({ color, size })}
                checked={checked}
                disabled={disabled}
                readOnly
            />
            <span>{label}</span>
        </label>
    );
}

See it in action

Colors

The Switch field includes 3 color variants: light, dark, and neutral. Like the Checkbox and Input recipes, these are neutral-spectrum surface colors rather than status colors — the color sets the off track, while the on-track fill (@color.primary) and its white knob stay the same across all three.

Each off track has a border that keeps 3:1 against the page in both light and dark mode, and its knob keeps 3:1 against the track. The neutral color uses one mid gray that meets both in either mode, which makes it the safest default for general-purpose forms.

Color Reference

ColorOff trackBorderKnobUse Case
light@color.gray-200@color.gray-500@color.gray-600Light surfaces, stays light in dark mode
dark@color.gray-700@color.gray-450@color.whiteDark surfaces, stays dark in light mode
neutral@color.gray-450@color.gray-450@color.whiteDefault color, the same in light and dark mode
Pro tip: Use neutral as your default switch color. Its track reads against both light and dark pages, so you don't need to manage light and dark tracks separately.

Sizes

Three size variants from sm to lg control the track dimensions and the knob, in rem, so the switch grows with the text. The knob is a radial-gradient() background-image that moves from the inline start of the track to the inline end when the switch turns on, with the travel expressed as calc(100% - 0.125rem) so it stays a uniform inset at every size.

Size Reference

SizeTrack (W×H)Knob
sm2rem × 1.125rem (32 × 18px)0.875rem (14px)
md2.25rem × 1.25rem (36 × 20px)1rem (16px)
lg2.75rem × 1.5rem (44 × 24px)1.25rem (20px)
Good to know: Pass the same size to the switchRecipe wrapper and the switchField switch so the label typography, gap, and track scale together. The track radius is always @border-radius.full, so it stays a pill at every size.

States

The field's states are styled from the <input> that exposes them, with :checked, :disabled, aria-readonly and aria-invalid, so what people see and what assistive technologies report can't drift apart. None of them changes the switch's size.

On

:checked recolors the track to @color.primary and moves the white knob to the inline end, so on and off differ by more than color. Bind the native checked attribute (or v-model / controlled value) as usual.

Disabled

:disabled dims the switch to 0.5 opacity and switches the cursor to not-allowed; the wrapper dims its label to match via :has(). Mirror it with the native disabled attribute so the input is also removed from the tab order.

Read-only

A checkbox has no readonly of its own, so a read-only switch sets aria-readonly="true" and your component cancels the click that would flip it. The recipe gives it a dashed border, with the fill stopping at the border so the dashes show against the page, and a default cursor on the field and its label. It can still be focused, and its form still sends it.

Invalid

Set aria-invalid="true" on the input while its error message shows, and link the message with aria-describedby. The border turns @color.error, doubled by a 1px inset shadow so the switch doesn't grow. The focus ring stays @color.focus.

Anatomy

The Switch is composed of two independent recipes: a label wrapper and the native input switch.

PartRecipeRole
WrapperuseSwitchRecipe()The .switch <label> — owns inline layout (gap, alignment), label typography, the hit area, and disabled-label dimming
FielduseSwitchFieldRecipe()The .switch-field native <input type="checkbox" role="switch"> — owns the track, knob, color surface, and on / focus / disabled / read-only / invalid states
<label class="switchRecipe(...)">
    <input type="checkbox" role="switch" class="switchField(...)" />
    <span>Enable notifications</span>
</label>

The wrapper dims its own label when it contains a disabled field, using :has(.switch-field:disabled), so a disabled switch and its text fade together without extra props.

Accessibility

The Switch recipes do their part of every stylesheet rule on the Open Components Switch page. The label, the error message and when to apply the setting are up to the screen that uses it. Here's what the recipes do:

  • Contrast. Every off track has a border of at least 3:1 against the page in light and dark mode, and its knob at least 3:1 against the track. The on-track is @color.primary with a white knob, which meets both too (WCAG 1.4.11). switchContrast.test.ts checks every color, on and off, in both modes. If you override the colors, check the same pairs.
  • More than color. On and off differ by the knob's position as well as the track's fill (WCAG 1.4.1).
  • Focus. A 2px solid outline with a 2px offset in @color.focus draws around the track on :focus-visible, in every state, invalid included (WCAG 2.4.7). The color.focus token defaults to @color.primary, so override it to change the ring of every component at once.
  • Size and touch. The track and the knob are sized in rem, so they grow with the text. The wrapper <label> is the switch's hit area: it's at least 24px tall (WCAG 2.5.8), and at least 44px on touch screens through the any-pointer-coarse modifier (WCAG 2.5.5), so wrap the field in it. No state changes the switch's size or position.
  • States. The invalid, read-only and disabled looks come from the input's aria-invalid="true", aria-readonly="true" and disabled attributes, through the aria-invalid, aria-readonly and disabled modifiers, so a switch only looks invalid while it says it is. Invalid shows through the border and an inset shadow, read-only through a dashed border and disabled through opacity.
  • Hover. The switch has no hover style of its own. Any hover style you add belongs behind the hover-capable modifier (&:hover-capable:hover), so a tap on a touch screen doesn't leave the switch looking hovered.
  • Motion. With the motion-reduce modifier, the knob jumps rather than slides when people ask for less motion (WCAG 2.3.3).
  • Forced colors and more contrast. In forced colors mode the field sets forced-color-adjust: none through the forced-colors modifier and draws itself in system colors: a Canvas track with a CanvasText border and knob while off, a Highlight track with a HighlightText knob while on, a Highlight focus ring and a GrayText disabled switch, which the field and the wrapper both show at full opacity. The read-only dashes and the invalid border's second pixel still show. With the contrast-more modifier, the border of an off, valid neutral switch takes the text color at full strength. light and dark switches keep their own fixed border, which holds 3:1 against the page in both modes, and an invalid switch keeps its error border.
  • Right to left. With the rtl modifier, the knob starts at the right and moves to the left, so on is on the left in right-to-left layouts.
  • Label every switch. Wrap the input and its text in the <label> (as the wrapper does) or associate a separate <label for="...">. The label names the setting and stays the same whether the switch is on or off.
  • Keep the native input. Styling the real <input type="checkbox"> with appearance: none preserves keyboard operation, focus order, and form submission for free.
  • Add role="switch". It keeps the native checkbox semantics (Space toggles, form submission) while telling assistive technology to announce "on / off" rather than "checked / unchecked".
  • Mirror disabled on the input. Set the real disabled attribute so the field leaves the tab order.

Customization

Overriding Defaults

Each switch composable accepts an optional second argument to override any part of the recipe configuration. Overrides are deep-merged with the defaults, so you only need to specify the properties you want to change:

src/components/switch.styleframe.ts
import { styleframe } from 'virtual:styleframe';
import { useSwitchFieldRecipe } from '@styleframe/theme';

const s = styleframe();

const switchField = useSwitchFieldRecipe(s, {
    defaultVariants: {
        color: 'neutral',
        size: 'lg',
    },
});

export default s;

Filtering Variants

If you only need a subset of the available variants, use the filter option to limit which values are generated. This reduces the output CSS and keeps your component API focused:

src/components/switch.styleframe.ts
import { styleframe } from 'virtual:styleframe';
import { useSwitchFieldRecipe } from '@styleframe/theme';

const s = styleframe();

// Only generate the neutral color
const switchField = useSwitchFieldRecipe(s, {
    filter: {
        color: ['neutral'],
    },
});

export default s;
Good to know: Filtering also removes compound variants and adjusts default variants that reference filtered-out values, so your recipe stays consistent.

API Reference

useSwitchRecipe(s, options?)

Creates the switch wrapper recipe — the .switch <label> that lays out the switch and label and dims the label when the nested field is disabled.

Parameters:

ParameterTypeDescription
sStyleframeThe Styleframe instance
optionsDeepPartial<RecipeConfig>Optional overrides for the recipe configuration
options.baseVariantDeclarationsBlockCustom base styles for the wrapper
options.variantsVariantsCustom variant definitions for the recipe
options.defaultVariantsRecord<keyof Variants, string>Default variant values for the recipe
options.filterRecord<string, string[]>Limit which variant values are generated

Variants:

VariantOptionsDefault
sizesm, md, lgmd

useSwitchFieldRecipe(s, options?)

Creates the switch field recipe — the .switch-field native <input type="checkbox" role="switch"> that owns the track, sliding knob, surface color, and native states. Accepts the same parameters as useSwitchRecipe.

Variants:

VariantOptionsDefault
colorlight, dark, neutralneutral
sizesm, md, lgmd

Learn more about recipes →

Best Practices

  • Pass size to both parts: Spread the same size to the wrapper and the field so the label and switch scale together.
  • Use neutral for general forms: The neutral track reads against light and dark pages alike, making it the safest default.
  • Reach for a switch, not a checkbox, for instant actions: Use a switch when flipping it takes effect immediately (settings); use a Checkbox when the choice is submitted with a form.
  • Mirror state on the native input: Set the real disabled, aria-readonly and aria-invalid attributes, since the recipe styles the switch from them.

FAQ