Creating a Stylish Toggle Switch Button in CSS3

Creating a Stylish Toggle Switch Button in CSS3

Enhance your UI with a sleek toggle switch button using pure CSS3! This tutorial demonstrates how to build an interactive and visually appealing toggle button without any JavaScript.

Checkout the demo in portfolio Toggle button CSS

How It Works

  1. HTML Structure: A <label> wraps the input checkbox and the slider.

  2. CSS Styling:

    • The slider has a default grey background and a circular knob.

    • When the input is checked, the slider changes to green, and the knob shifts to the right using CSS transitions.

Code Snippet

Here’s the complete code for creating a toggle switch button:

HTML Structure

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

CSS

.container{
  cursor: pointer;
  transform: scale(1);
  margin: 20px auto 50px auto;
  display: block;
  width: 80px;
}
.cB{
  display: none;
}
.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);
}
/***Adding tranisitons***/
.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);
}
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);
}

This simple yet elegant design is perfect for modern web applications! Try it out and customize it to suit your style.

Happy coding! 😊