How to Create a Toggle Switch With CSS

As a front-end developer, one of the most common UI elements you’ll encounter is the toggle switch.

It’s a simple and elegant solution for letting users toggle between two states, such as on and off, yes and no, or true and false.

In this tutorial, we’ll show you how to create a toggle switch using only CSS.


What is a Toggle Switch – On/Off Button

A toggle switch is a UI element that allows users to toggle between two states, such as on and off.

It’s often used as an alternative to traditional checkboxes and radio buttons, as it’s more intuitive and easier to use.

HTML Markup

Let’s start by creating the HTML markup for our toggle switch. Here’s what it should look like:

<label class="switch">
  <input type="checkbox">
  <span class="slider"></span>
</label>

We’re using a label element to wrap around our input element and our slider element.

The input element is a checkbox, which will be used to keep track of the toggle switch’s state. The slider element will be used to visually represent the toggle switch.

CSS Styling

Next, we’ll add some CSS styles to our toggle switch. Here’s what the CSS should look like:

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

In the CSS, we’re using absolute positioning and transforms to move the slider element back and forth, depending on the toggle switch’s state.

When the toggle switch is turned on, the slider element is moved to the right, and when it’s turned off, it’s moved back to the left.


Conclusion

That’s all there is to creating a toggle switch with CSS!