Presently, generating flip switch button (on off) using CSS is very novel concept amongst designers. Therefore in this blog, I am going to explain how to design On/Off flip switch custom button using CSS3 transitions.
How to create custom flip switch button?
Initially, start from html div structure. Inside the div we would need one <input> tag with type checkbox.
Refer the below HTML code:
<div class="switchbutton">
<input type="checkbox" name="onoffswitch" class="switchbutton-checkbox" id="myonoffswitch" checked/>
<label class="switchbutton-label" for="myonoffswitch">
<span class="switchbutton-inner"></span>
<span class="switchbutton-switch-btn"></span>
</label>
</div>
Next step is styling with CSS3
.switchbutton {
position: relative;
width: 80px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.switchbutton-checkbox {
display: none;
}
.switchbutton-label {
display: block;
overflow: hidden;
cursor: pointer;
border: 1px solid #999999;
border-radius: 20px;
height: 30px;
}
.switchbutton-inner {
display: block;
width: 200%;
margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.switchbutton-inner:before,
.switchbutton-inner:after {
float: left;
width: 50%;
height: 30px;
box-sizing: border-box;
}
.switchbutton-inner:before {
content: "";
padding-left: 10px;
background-color: #31D5BE;
color: #FFFFFF;
}
.switchbutton-inner:after {
content: "";
padding-right: 10px;
background-color: #CCCCCC;
color: #333333;
text-align: right;
}
.switchbutton-switch-btn {
display: block;
width: 32px;
margin: 0px;
background: #000000;
position: absolute;
top: 0;
bottom: 0;
right: 48px;
transition: all 0.3s ease-in 0s;
border-radius: 20px;
}
.switchbutton-checkbox:checked + .switchbutton-label .switchbutton-inner {
margin-left: 0;
}
.switchbutton-checkbox:checked + .switchbutton-label .switchbutton-switch-btn {
right: 0px;
}
Next is to proceed with switch button animation using css3 ‘transition’. Here, the button width is 32px and position is ‘absolute’ having values top: 0 and bottom: 0. Now, we calculate the value of right side.
The class ‘.switchbutton’ width is 80px and class ‘.switchbutton-switch-btn’ width is 32px. So we deduct the value 32px (.switchbutton-switch-btn) from 80px (.switchbutton). Whatever value is generated is assigned to the right side i.e. right: 48px.
. switchbutton -switch-btn {
display: block;
width: 32px;
margin: 0px;
background: #000000;
position: absolute;
top: 0;
bottom: 0;
right: 48px;
transition: all 0.3s ease-in 0s;
border - radius: 20px;
}
Here's how the switch button will look like -