CSS Material Toggle Switch

An Android-style switch made from a single input, with a slim track, an oversized thumb and a focus halo.

  • material design
  • android
  • toggle
  • switch
  • single element
  • appearance
HTML
<label class="tgl-md">
  <input type="checkbox" role="switch" checked>
  Dark theme
</label>
CSS
.tgl-md {
  display: inline-flex;
  align-items: center;
  gap: 14px;
  color: #3b0764;
  font: 500 15px system-ui, sans-serif;
  cursor: pointer;
}

.tgl-md input {
  position: relative;
  width: 36px;
  height: 14px;
  margin: 0 4px;
  border-radius: 999px;
  background: #d4d4d8;
  -webkit-appearance: none;
  appearance: none;
  cursor: pointer;
  transition: background 0.2s ease;
}

.tgl-md input::before {
  content: "";
  position: absolute;
  top: 50%;
  left: -4px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: #fafafa;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  transform: translateY(-50%);
  transition: transform 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;
}

.tgl-md input:checked {
  background: #d8b4fe;
}

.tgl-md input:checked::before {
  background: #7e22ce;
  transform: translate(22px, -50%);
}

.tgl-md input:focus-visible {
  outline: none;
}

.tgl-md input:focus-visible::before {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4), 0 0 0 10px rgba(126, 34, 206, 0.18);
}

@media (prefers-reduced-motion: reduce) {
  .tgl-md input,
  .tgl-md input::before {
    transition: none;
  }
}

About this CSS Material Toggle Switch

This CSS Material Toggle Switch is 59 lines of pure CSS (1.1 KB) with no JavaScript and no dependencies. It uses transitions, transforms, box shadows and Flexbox. It works in current versions of Chrome, Edge, Safari and Firefox. It works in any stack: plain HTML, React, Vue, Svelte, Astro, WordPress or Webflow.

CSS features used

Customize it

The colors in this snippet. Search and replace them to match your brand:

  • #3b0764
  • #d4d4d8
  • #fafafa
  • #d8b4fe
  • #7e22ce

How to use this material toggle switch

  1. Copy the HTML and paste it where you want the element to appear.
  2. Copy the CSS into your stylesheet, or inside a <style> tag.
  3. Keep the .tgl-md class name, or rename it in both places. Then tweak colors, sizes and timing to match your design.
  4. Using React or Next.js? Change class to className in the HTML. The CSS works as is, including in Tailwind projects (put it in your global stylesheet).

Building with an AI tool?

“Copy for AI” copies a short prompt for Cursor, Claude Code, Lovable, Bolt or v0. Your AI tool opens the Markdown version of this snippet and reads the HTML, CSS and setup notes there. If your tool can't open links, with the code instead. More ways to use copy CSS with AI.

Feedback