Switch
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:
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:
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
| Color | Off track | Border | Knob | Use Case |
|---|---|---|---|---|
light | @color.gray-200 | @color.gray-500 | @color.gray-600 | Light surfaces, stays light in dark mode |
dark | @color.gray-700 | @color.gray-450 | @color.white | Dark surfaces, stays dark in light mode |
neutral | @color.gray-450 | @color.gray-450 | @color.white | Default color, the same in light and dark mode |
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
| Size | Track (W×H) | Knob |
|---|---|---|
sm | 2rem × 1.125rem (32 × 18px) | 0.875rem (14px) |
md | 2.25rem × 1.25rem (36 × 20px) | 1rem (16px) |
lg | 2.75rem × 1.5rem (44 × 24px) | 1.25rem (20px) |
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.
| Part | Recipe | Role |
|---|---|---|
| Wrapper | useSwitchRecipe() | The .switch <label> — owns inline layout (gap, alignment), label typography, the hit area, and disabled-label dimming |
| Field | useSwitchFieldRecipe() | 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.primarywith a white knob, which meets both too (WCAG 1.4.11).switchContrast.test.tschecks 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.focusdraws around the track on:focus-visible, in every state, invalid included (WCAG 2.4.7). Thecolor.focustoken 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 theany-pointer-coarsemodifier (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"anddisabledattributes, through thearia-invalid,aria-readonlyanddisabledmodifiers, 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-capablemodifier (&:hover-capable:hover), so a tap on a touch screen doesn't leave the switch looking hovered. - Motion. With the
motion-reducemodifier, 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: nonethrough theforced-colorsmodifier and draws itself in system colors: aCanvastrack with aCanvasTextborder and knob while off, aHighlighttrack with aHighlightTextknob while on, aHighlightfocus ring and aGrayTextdisabled 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 thecontrast-moremodifier, the border of an off, validneutralswitch takes the text color at full strength.lightanddarkswitches 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
rtlmodifier, 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">withappearance: nonepreserves 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
disabledon the input. Set the realdisabledattribute 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:
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:
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;
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:
| Parameter | Type | Description |
|---|---|---|
s | Styleframe | The Styleframe instance |
options | DeepPartial<RecipeConfig> | Optional overrides for the recipe configuration |
options.base | VariantDeclarationsBlock | Custom base styles for the wrapper |
options.variants | Variants | Custom variant definitions for the recipe |
options.defaultVariants | Record<keyof Variants, string> | Default variant values for the recipe |
options.filter | Record<string, string[]> | Limit which variant values are generated |
Variants:
| Variant | Options | Default |
|---|---|---|
size | sm, md, lg | md |
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:
| Variant | Options | Default |
|---|---|---|
color | light, dark, neutral | neutral |
size | sm, md, lg | md |
Best Practices
- Pass
sizeto both parts: Spread the samesizeto the wrapper and the field so the label and switch scale together. - Use
neutralfor 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-readonlyandaria-invalidattributes, since the recipe styles the switch from them.
FAQ
<input type="checkbox" role="switch"> with appearance: none keeps the control fully native: Space toggles it, it participates in form submission, and :checked / :disabled / :focus-visible drive the styling with zero runtime JavaScript. A custom <div> would need ARIA roles and keyboard handlers to match.readonly attribute doesn't apply to checkboxes. A read-only switch sets aria-readonly="true", which assistive technologies announce, and cancels the click that would flip it, so the recipe styles it from that attribute.filter option, compound variants that reference filtered-out colors are automatically removed, and default variants are adjusted if they reference a removed value — so the recipe stays consistent and only emits the CSS you use.Slider
An input control for selecting a value from a range by dragging a thumb along a track. Composed of a root, track, range, and thumb recipe, with color, size, and orientation options through the recipe system.
Textarea
A multi-line text-field component with a wrapper-owned visual surface, inline prefix/suffix addons, a resize axis, and invalid/disabled/readonly states. Supports light, dark, and neutral colors, default/soft/ghost styles, and three sizes through the recipe system.