Toggle
MYDS-compliant toggle component for seamless transition starting point from HTML/CSS to React
Overview
The MYDS HTML/CSS Toggle (Switch) is a lightweight, accessible interaction component used to toggle between two states. It is built using semantic HTML (checkboxes) and CSS transitions to provide a native-feel experience with three standardized sizes.
1. Setup
Import the following stylesheets to ensure the toggle displays correctly.
This guarantees that:
- The CSS reset applies first.
- The toggle base styles override the reset where necessary.
- The dark theme styles apply last, so they can override both the reset and base button styles when needed.
2. Usage
To implement a toggle, wrap a hidden input and a track span inside a label. Apply the size modifier (sm, md, or lg) to both the label and the track.
3. Sizes
Small (sm)
Medium (md)
Large (lg)
4. States
The toggle handles the following states automatically through the native checkbox:
- Unchecked: Default state with a neutral gray track.
- Checked: Primary blue track with the thumb translated horizontally.
- Hover: Subtle background color shift on the track.
- Focused: Accessible 2px ring visible during keyboard navigation (
Tab). - Disabled: Input becomes non-interactive (Add
disabledattribute to the input).
5. Anatomy
| Selector | Purpose |
|---|---|
.toggle-label-myds | Wrapper that defines the hit area. |
.toggle-input-myds | Hidden native checkbox managing the state. |
.toggle-track-myds | The visual background/container of the toggle. |
.toggle-thumb-myds | The sliding white circle component. |
.track-[size]-myds | Controls size-specific dimensions and translation math. |
6. Customization
You can change the "active" color by overriding the checked state:
7. Accessibility
- Semantic: Uses
<input type="checkbox">so screen readers identify it as a toggle/switch.- Keyboard Support: Fully navigable via
SpaceandTab. - Aria-Labels: For better UX, it is recommended to add
aria-label="Toggle setting name"to the input.
- Keyboard Support: Fully navigable via