Framework
HTML
Built off Sass this can be used with any framework but, if your framework is supported, it's advised to use the official component
Usage
- Pick the toggle you want to use from here
- Add the css into your <head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/{toggle name}.min.css">
Find the full list of css from JSDelivr including SRI
- Copy the corresponding html for the toggle of your choice, found on each toggles page
Toggling
When using the button or div wrappers, we need to add the toggle class theme-toggle--toggled.
<button class="theme-toggle theme-toggle--toggled" type="button" aria-label="Toggle theme">
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
class="theme-toggle__dark-side"
fill="currentColor"
viewBox="0 0 512 512"
>
<path d="M256 0a256 256 0 1 0 0 512 256 256 0 0 0 0-512Zm0 464V48a208 208 0 0 1 0 416Z" />
</svg>
</button>
The checkbox wrapper manages the toggling on its own. You can manipulate this like you would with any checkbox
Styling
The toggles use currentColor for their SVGs. To change the color of a toggle, simply change the css color property of the component.
Animation duration
Each toggle uses a css variable to store the duration of the animation in ms. It defaults to 500ms. The css variable is added onto the outer layer of the toggle via the theme-toggle class. To override it you should apply your new value onto the svg.
Reversed
Each toggle is reversible by adding the theme-toggle--reversed class onto the wrapper.
<button class="theme-toggle theme-toggle--reversed" type="button" aria-label="Toggle theme">
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
class="theme-toggle__dark-side"
fill="currentColor"
viewBox="0 0 512 512"
>
<path d="M256 0a256 256 0 1 0 0 512 256 256 0 0 0 0-512Zm0 464V48a208 208 0 0 1 0 416Z" />
</svg>
</button>
You can also copy the reversed toggle code via the toggle page.
Accessability
For all the wrappers, it's recommend that you apply an appropriate title. This is done by default on the copied code for each toggle.
When using the button wrapper, it's recommend that you apply an appropriate aria-label. This is done by default on the copied code for each toggle.
When using the checkbox, we need to apply an appropriate label with hidden text for a screen reader. Each toggle comes with a <span> containing this text.
When using the div, we can add hidden text for a screen reader. Each toggle comes with a <span> containing this text.
You should also apply a relevant tabIndex attribute
Although it's provided, the div wrapper isn't preferred due to the lack of native accessability.
Reduced Motion
This library respects reduced motion and removes the animations when a client has this enabled.
Disabling reduced motion
It's possible to always force the animation by adding the .theme-toggle--force-motion class to your wrapper