How can we help?Get in touch
Nowadays it's more common to find fully customized form elements that enhance the user experience.
In this article we will see how to turn a typical checkbox into a switch that is much more modern and visually appealing.
Let's see an example of how this switch would be used in the typical options in a user area:
Publish my email address
Receive newsletter
Receive email notifications
First we need to define the html. We are going to use the labels and input tags of a typical checkbox and an extra div that will serve to do the trick with css.
HTML
- <label class="switch">
- <input type="checkbox">
- <div class="slider round"></div>
- </label>
Now let's go with the css:
CSS
- /* Format the label that will serve as container */
- .switch {
- position: relative;
- display: inline-block;
- width: 60px;
- height: 34px;
- }
- /* Hide the html checkbox */
- .switch input {
- display:none;
- }
- /* Format the switch box on which the control knob or slider will slide */
- .slider {
- position: absolute;
- cursor: pointer;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: #ccc;
- -webkit-transition: .4s;
- transition: .4s;
- }
- /* Depict the control knob or slider using the pseudo-selector before */
- .slider:before {
- position: absolute;
- content: "";
- height: 26px;
- width: 26px;
- left: 4px;
- bottom: 4px;
- background-color: white;
- -webkit-transition: .4s;
- transition: .4s;
- }
- /* We change the background color when the checkbox is activated */
- input:checked + .slider {
- background-color: #E27AD8;
- }
- /* We slide the slider to the right when the checkbox is activated */
- input:checked + .slider:before {
- -webkit-transform: translateX(26px);
- -ms-transform: translateX(26px);
- transform: translateX(26px);
- }
- /* We apply a rounded edge effect to the slider and to the bottom of the slide */
- .slider.round {
- border-radius: 34px;
- }
- .slider.round:before {
- border-radius: 50%;
- }
That's all folks! Now we know how to create a toggle switch or switch with css. Easy, fast and for the whole family!
Main photo: Pierre Chatel
Related works
Platform for online claims
Fun musical spanish