State toggle
One boolean state that a button flips, and styles that follow it.
Live previewreal runtime
Click the switch, or Tab to it and press Enter or Space.
state
| name | value | previous | changes |
|---|---|---|---|
| Waiting for the preview to start. | |||
events
- Interact with the preview to record events.
How it works
- toggle()line 4Flips a boolean state. In an :on() rule it is the mutation --open: toggle().
- :when()lines 7, 8Matches elements for which the condition is true, with states resolved from that element.
A boolean state flipped by toggle(). :when(--on) turns whole rules on and off, when() picks the label, and --attr-aria-pressed keeps the button’s aria-pressed attribute in sync.
Native CSS alternative
A checkbox and :checked style a two-state control without any script, and are the right choice inside a form. A button with aria-pressed is the pattern for a toggle that is not a form value; keeping that attribute in sync is what needs a script without Reactive CSS.
Limitations
- The state is not stored: a reload turns the switch off again.
Implementation
2 files · 10 linesstyle.cssreactive
/* ---- Reactive CSS -------------------------------------------------------------------------- */.toggle { --on: state(false); }.toggle .switch:on(click) { --on: toggle(); }/* The stored state shows up in three places. */.toggle:when(--on) .track { background: var(--accent); }.toggle:when(--on) .knob { translate: 20px 0; }.toggle .label { content: when(--on, "On", "Off"); }.toggle .switch { --attr-aria-pressed: var(--on); } /* the button reports its state */state()Function · hover any red tokenMakes each matching element the owner of an independent state with an initial value.Reference →
Source: site/src/catalog/api/state-toggle/. style.css from its Reactive CSS divider; the layout above it and the shared api.css run but are not shown.
Next recommendedForm mirror →Type in the field and the preview follows; the Clear button resets both.← All examples
Related