In previous article, I mentioned Creating Toggle (Switch) button using Javascript and HTML but in this article, I have mentioned how we can create Toggle switch with Text in CSS only.
So let's consider we have below HTML Code
<label class="switch">
<input type="checkbox" id="togBtn">
<div class="toggle round"></div>
</label>
Then to create a Toggle with text using CSS only, we will have below CSS Code
.switch {
position: relative;
display: inline-block;
width: 90px;
height: 34px;
}
.switch input {display:none;}
.toggle {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}
.toggle:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 50%;
}
input:checked + .toggle {
background-color: #2ab934;
}
input:focus + .toggle {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .toggle:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(55px);
}
/*------ CSS to change text with transform animation ---------*/
.toggle:after
{
content:'YES';
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked + .toggle:after
{
content:'NO';
}
You can see working fiddle here:
As you will see above code, we have used CSS code to hide the initial checkbox to convert it into a toggle.
Then we use .toggle
class with div to create an element like a switch button.
.toggle {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}
Once we have a div like button, we add a small white circle-like button using the below CSS
.toggle:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 50%;
}
Once we have switch like toggle using CSS, we are adding text inside toggle using the below CSS psuedo elements
.toggle:after
{
content:'YES';
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}
input:checked + .toggle:after
{
content:'NO';
}
That's it.
You may also like to read:
Preview Images before upload using Javascript
Styling Input type="file" button using CSS & Bootstrap
Useful CSS animation examples with code & animation basics
How to add double quotes in javascript string?
Creating Multi-Line String in Javascript
Replace all occurrences in string using Javascript