CSS – round toggle switch using checkbox and label

Css round toggle switch can be implemented using html checkbox and a label tag which appears after it. The high level approach steps are:

  1. We make the checkbox invisible using display:none.
  2. The label uses attribute for=”cb_id” so that it handles the click for the checkbox. Also note that label appears immediately after checkbox.
  3. We draw a rectangle on label element which acts as background for toggle switch.
  4. We use :after to draw a circle which will move left or right.
  5. Using :checked style, we move the circle change background color of toggle switch.

Example

<style>
input.toggle-round {
  display:none;
}
input.toggle-round + label {
  display: block;
  position: relative;
  cursor: pointer;
}
input.toggle-round + label {
  padding: 1px;
  width: 100px;
  height: 50px;
  background-color: #ddd;
  border-radius: 50px;
  border: 1px solid #ccc;
}
input.toggle-round + label:after {
  display: block;
  position: absolute;
  content: "";
  width: 50px; height: 50px;
  background-color: white;
  border-radius: 100%;
  box-shadow: 0 2px 3px #888;
  transition: margin 0.5s;
}
input.toggle-round:checked + label {
  background-color: lightblue;
}
input.toggle-round:checked + label:after {
  margin-left: 50px;
}
</style>

<input id="cb_id" class="toggle-round" type="checkbox">
<label for="cb_id"></label>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments