Convert Checkbox To Toggle Button Using CSS

In this tutorial we will Convert Checkbox To Toggle Button Using CSS. We have used before and after selectors of CSS for this purpose.

HTML Code

HTML Code is given below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert Checkbox To Toggle Button Using CSS</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <div> 
    <input class='check' id="toggle" type="checkbox"/>
    <label for="toggle" class="button"></label>
  </div>
</body>
</html>

CSS Code

CSS Code is given below. In this code we used before and after selectors to transform the label element into the toggle button, the label element is also linked with the HTML checkbox element using it's id. With this, clicking on label of checkbox will check or uncheck it.

body
{
  background-color: #22438C;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  padding: 0;
}
.check{
  display: none;
}
.button {
  position: relative;
  display: block;
  width: 200px;
  height: 50px;
}
.button::before,
.button::after {
  content: "";
  display: block;
  position: absolute;
  cursor: pointer;
}
.button::before {
  width: 100%;
  height: 100%;
  background-color: #bbb;
  border-radius: 25px;
  border: 1px solid #333;    
  transition: background-color 0.5s ease;
}
.button::after {
  top: 0;
  left: 0;
  width: 25%;
  height: 100%;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0px 0px 5px 1px #000;    
  transition: left 0.5s ease;
}
.check:checked + .button::before {
  background-color: #C90011;
}
.check:checked + .button::after {
  left: 75%;
}

Video Tutorial

Watch video tutorial on how to Convert Checkbox To Toggle Button Using CSS.