Skip to content

Switch Examples

The examples below assume that you have imported the component and set up the theme.

Basic

Add a switch that works like a form input. A <label for> that points at the switch names it and toggles it on click.

--checked
State
<div class="switch-basic">
<label for="wifi-switch">Wi-Fi</label>
<sv-switch id="wifi-switch"></sv-switch>
</div>
<style>
.switch-basic {
display: flex;
gap: 4em;
align-items: center;
justify-content: center;
label {
cursor: pointer;
}
}
</style>

Icons

Replace or remove the icons inside the switch. The checked-icon and unchecked-icon slots swap them, an empty element in the background slot removes them, and the thumb slot fills the thumb.

<div class="switch-icons">
<div class="row">
<label for="switch-text-icons">Text icons</label>
<sv-switch id="switch-text-icons" class="text-icons" checked>
<strong aria-hidden="true" slot="checked-icon">On</strong>
<span aria-hidden="true" slot="unchecked-icon">Off</span>
</sv-switch>
</div>
<div class="row">
<label for="switch-no-icons">No icons</label>
<sv-switch id="switch-no-icons">
<span slot="background"></span>
</sv-switch>
</div>
<div class="row">
<label for="switch-thumb-icon">Icon in the thumb</label>
<sv-switch id="switch-thumb-icon" class="thumb-icons">
<span slot="background"></span>
<div class="custom-thumb" aria-hidden="true" slot="thumb">
<svg class="unchecked" viewBox="0 -960 960 960">
<path
d="m256-200-56-56 224-224-224-224 56-56 224 224 224-224 56 56-224 224 224 224-56 56-224-224-224 224Z"
/>
</svg>
<svg class="checked" viewBox="0 -960 960 960">
<path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z" />
</svg>
</div>
</sv-switch>
</div>
</div>
<style>
.switch-icons {
display: grid;
gap: 0.75em;
max-inline-size: 16rem;
margin-inline: auto;
.row {
display: flex;
gap: 0.5em;
align-items: center;
label {
flex: 1;
cursor: pointer;
}
}
.text-icons {
[slot="checked-icon"],
[slot="unchecked-icon"] {
font-size: 0.6em;
}
}
.thumb-icons {
.custom-thumb {
display: grid;
place-items: center;
inline-size: 100%;
block-size: 100%;
svg {
--icon-timing: var(--sv-switch-dur, 350ms)
var(--sv-switch-ease, cubic-bezier(0.486, 1.45, 0.2, 1));
grid-area: 1 / 1;
inline-size: 1.1em;
block-size: 1.1em;
transition:
opacity var(--icon-timing),
scale var(--icon-timing);
@media (prefers-reduced-motion: reduce) {
--icon-timing: 0s;
}
}
.checked {
opacity: 0;
fill: var(--sv-accent);
scale: 0;
}
.unchecked {
opacity: 1;
fill: var(--sv-gray-5);
scale: 1;
}
}
&:state(--checked) .custom-thumb {
.checked {
opacity: 1;
scale: 1;
}
.unchecked {
opacity: 0;
scale: 0;
}
}
}
}
</style>