← All Examples

Toggle Switch

A styled on/off toggle built with a checkbox and CSS.

Published May 19, 2026

Demo

HTML

<label class="toggle-label">
  <input class="toggle-input" type="checkbox">
  <span class="toggle-track"></span>
  Toggle me
</label>

CSS

.toggle-label {
  display: inline-flex;
  align-items: center;
  gap: 1rem;
  cursor: pointer;
}

.toggle-input {
  display: none;
}

.toggle-track {
  width: 52px;
  height: 28px;
  background: #ccc;
  border-radius: 999px;
  position: relative;
  transition: background .25s;
}

.toggle-track::after {
  content: "";
  position: absolute;
  top: 3px;
  left: 3px;
  width: 22px;
  height: 22px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 1px 4px rgba(0,0,0,.2);
  transition: transform .25s;
}

.toggle-input:checked + .toggle-track {
  background: #5b4cdb;
}

.toggle-input:checked + .toggle-track::after {
  transform: translateX(24px);
}

How it works

The trick is hiding the real checkbox with display:none and using an adjacent sibling <label> element as the visual track. The ::after pseudo-element acts as the thumb. When the checkbox is :checked, CSS shifts the thumb with translateX and changes the track color — no JavaScript needed.