Toggle Switch - Component
Code
Source (Nunjucks)
<label class="toggle-switch" for="{{ data.inputId }}">
<span class="toggle-switch__label {{ 'visually-hidden' if data.hiddenLabel }}">{{ data.label }}</span>
<input type="checkbox" role="switch" class="toggle-switch__input" id="{{ data.inputId }}" />
<div class="toggle-switch__decor focus-ring" aria-hidden="true">
<div class="toggle-switch__thumb"></div>
</div>
</label>
Output
<label class="toggle-switch" for="toggle-switch">
<span class="toggle-switch__label">Dark theme</span>
<input
type="checkbox"
role="switch"
class="toggle-switch__input"
id="toggle-switch"
/>
<div class="toggle-switch__decor focus-ring" aria-hidden="true">
<div class="toggle-switch__thumb"></div>
</div>
</label>
Information
The toggle switch extends a standard checkbox by adding a switch
role and
switch-like decorative styling.
It's really important that the input (toggle-switch__input
) sits before
the decor (toggle-switch__decor
) because the Sass block uses [next sibling
combinator selectors]
(/learn/css/selectors/#next-sibling-combinator) to create
visual state changes.
You can visually hide the text label with the visually-hidden
utility, but
this pattern must contain one for accessibility purposes.
Key links
Variants
Hidden label
Code
Source (Nunjucks)
<label class="toggle-switch" for="{{ data.inputId }}">
<span class="toggle-switch__label {{ 'visually-hidden' if data.hiddenLabel }}">{{ data.label }}</span>
<input type="checkbox" role="switch" class="toggle-switch__input" id="{{ data.inputId }}" />
<div class="toggle-switch__decor focus-ring" aria-hidden="true">
<div class="toggle-switch__thumb"></div>
</div>
</label>
Output
<label class="toggle-switch" for="toggle-switch">
<span class="toggle-switch__label visually-hidden">Dark theme</span>
<input
type="checkbox"
role="switch"
class="toggle-switch__input"
id="toggle-switch"
/>
<div class="toggle-switch__decor focus-ring" aria-hidden="true">
<div class="toggle-switch__thumb"></div>
</div>
</label>