TL;DR In this article I will show how we can create a toggle button with SCSS.
This is a two steps solutions, the first step is writing the HTML container and the second step is writing the actual SCSS.
Step 1: HTML
The HTML is really simple, we are wrapping a checkbox input and a div element inside label tag. We do it because we want to toggle the checkbox not only when we click the button itself but in any place around it (our graphics), where the label is defined.
We are using the
<div class="toggle-button">element for two reasons:
Reason 1: We want to change the background color when the state is changed.
Reason 2: We want to create the round white button by using css pseudo element.
Note: we could use any other element, however div is more convenient for this cause.
Step 2: CSS (SCSS)
After we understood the building blocks of the HTML presenting layer, we need to understand the actual CSS which doing the visualization.
The CSS can be broken down to its selectors — for simplicity, and later adding the CSS properties.
As you might be aware, selectors is our way of finding elements and changing their style.
Below is the simple selector code with comments:
Now lets see the full style, that build upon the selectors above:
To play with an actual running code, click Here