Dark Mode Toggle Button

Implement a stylish dark/light mode switch for your website using pure CSS and minimal JavaScript. Fully customizable and lightweight.

Dark Mode Toggle Button

This snippet provides a visually appealing dark/light mode toggle button for websites. It uses a checkbox input styled entirely with CSS to switch between sun ☀️ and moon 🌙 icons while toggling page colors smoothly. Ideal for enhancing UX and accessibility.

  • How to use: Copy the HTML, CSS, and JS code below into your project. Ensure IDs match.
  • Change colors: Adjust background-color and box-shadow in .toggle-slider for custom themes.
  • Adjust effect: Modify transition duration for smoother or faster animations. Replace icons as desired.
<label class="toggle">
  <input type="checkbox" id="darkModeToggle">
  <span class="toggle-slider"></span>
</label>

<style>
.toggle {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 36px;
}

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

.toggle-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f1f1f1;
  border-radius: 36px;
  transition: background-color 0.4s ease;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.toggle-slider::before {
  content: "☀️";
  position: absolute;
  height: 28px;
  width: 28px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 28px;
  transition: transform 0.4s, content 0.4s;
}

input:checked + .toggle-slider {
  background-color: #222;
}


input:checked + .toggle-slider::before {
  transform: translateX(34px);
  content: "🌙";
}
</style>
<script>
// Optional JS: toggle page dark mode
document.getElementById('darkModeToggle').addEventListener('change', function() {
  document.body.classList.toggle('dark', this.checked);
});
</script>

<style>
body.dark {
  background-color: #121212;
  color: #ffffff;
  transition: background-color 0.4s, color 0.4s;
}
</style>
← Back to Snippets