Bootstrap switches with on-off labels
Posted
on
Apple’s iOS, iPadOS and macOS all feature an accessibility option to add labels to switches. This can be helpful for users who may not be able to distinguish between the on and off states of a switch via color alone.
It’s easy to add this feature to Bootstrap switches using a little CSS. Here’s how you can do it.
.form-switch .form-check-input::after {
font-size: 0.5rem;
position: absolute;
margin-top: 1.4px;
}
.form-switch .form-check-input:checked::after {
color: #fff;
content: "⼁";
margin-left: 5px;
}
.form-switch .form-check-input:not(:checked)::after {
color: #bfbfbf;
content: "○";
margin-left: 22px;
}
Demo
Codepen Demo
You can also view the demo on Stackblitz.
Notes and Observations
- The CSS above works in both light and dark mode.
- I add the
switchattribute to the input element to give the switches haptic feedback on iPhones. - The
::afterpseudo-element is used to add the labels. - The
contentproperty is used to add the labels. - The
margin-leftandmargin-topproperties are used to position the labels. - The
font-sizeandcolorproperties are used to style the labels.