A common element in many web apps is the toggle button (also called a toggle switch or just a toggle), which enables the user to turn a setting or option on or off. Yes, you could use a checkbox for that, but a toggle button adds visual interest because it includes a “switch” that slides right and left to indicate the button is on and off. Here’s an example:
Note that when you click the toggle button to the “on” position, not only does the switch slide to the right, but the background color also changes to give the user a visual indication of the state change. Here’s the code:
In the HTML Editor, we have a div
element that serves as the toggle button’s label (and, as you’ll see, the text changes to indicate the current state of the toggle button). The toggle itself is composed of two elements: an input
element with type="checkbox"
. We don’t use this checkbox directly, however, so it’s hidden via class="hide-me"
(described below). The toggle button itself is given by the label
element, which is tied to the checkbox using for="cb-toggle"
(which is the id
value used by the input
element) and class="toggle"
(also described below).
Now let’s check out the CSS:
.toggle
{…
<label
class="toggle">
tag).
position: relative;
::after
pseudo-element (discussed below).
display: inline-block;
…
background-color: hsl(0, 0%, 85%);
border-radius: 25px;
cursor: pointer;
transition: background-color 0.25s ease-in;
background-color
value, which changes when the button is toggled (see line 23).
.toggle::after
{…
content: '';
position: absolute;
…
2px
offset from the top left of the toggle.
width: 22px;
…
background-color: white;
border-radius: 50%;
transition: all 0.25s ease-out;
transform
property (see line 28) shifts the switch right (when it’s on) and left (when it’s off).
#cb-toggle:checked + .toggle
toggle
class) when the checkbox element (#cb-toggle
) is checked.
background-color: hsl(102, 58%, 39%);
#cb-toggle:checked + .toggle::after
toggle::after
pseudo-element) when the checkbox element (#cb-toggle
) is checked.
transform: translateX(24px);
24px
to the right when the button is toggled to the “on” position. Lines 26 and 27 are the vendor-prefixed versions of the transform
property;
.hide-me
…
opacity
, height
, and width
to 0.