Toggle button with css3

Toggle button switch

Hi… 🙂 Here is the simple fun interaction for toggle button with css3.  In this tutorial, I focused on how to create switch button, I’ll show you how to create an on/off switch with CSS without using javascript. Let’s see how it’s working.

 

Read Also: Animated Elastic Switch Button using CSS3

 

How is it working?

Basic thing for the checkbox is which is either checked or unchecked. Instead of browser default checkbox, We can customize(ie. checkbox hack).

The checkbox hack allows us to have a toggle handler in pure CSS using :checked pseudo-selector, and a sibling selector (~ or +). Basically, say “if the checkbox is checked, then the following X element have separate styles”.

HTML Element

<label class=”container”>
<input type=”checkbox” class=”cB” />
<div class=”cB-outer-div”>
<div class=”cB-inner-div”></div>
</div>
</label>

CSS

Apply styles to the inner and outer element.

.cB-outer-div{
display: inline-block;
position: relative;
width: 80px;
height: 30px;
background: #ff6454;
border-radius: 20px;
}
.cB-inner-div{
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
background: #c0392b;
border-radius: 50%;
top: -10px;
box-shadow: 2px 0px 4px 0px rgba(0,0,0,0.25);
}

Set initial state of the switch button (ie)Checkbox uncheck state

.cB-inner-div{
transform: translateX(0px);
}
.cB-outer-div, .cB-inner-div{
transition: 0.3s all cubic-bezier(0.215, 0.61, 0.355, 1);
}

Set final state of the switch button (ie)Checkbox checked state

input[type=”checkbox”].cB:checked + .cB-outer-div{
background: #2ecc71;
}
input[type=”checkbox”].cB:checked + .cB-outer-div .cB-inner-div{
background: #27ae60;
transform: translateX(30px);
box-shadow: -2px 0px 4px 0px rgba(0,0,0,0.2);
}

Thatsall. Check the demo
Thank you for reading this tutorial, and if you have any question or related work to show, please do. ?

You may also like