How to Implement a Light/Dark Theme Switcher with CSS Variables

Offering light and dark themes on websites is no longer just a trend—it’s an expectation. Whether to reduce eye strain in low-light environments or simply to suit personal aesthetics, users appreciate having control over a site’s appearance. In this guide, we will explore how to create an elegant light/dark theme switcher using CSS custom properties and localStorage. We’ll also make the toggle switcher visually appealing and responsive to the user’s OS theme preferences.

See the Pen Theme licht/dark switcher by Andrei Surdu (@Andrei-Surdu) on CodePen.

Define Custom Properties for Light and Dark Themes

Begin by setting up the CSS variables for both light and dark themes:

/* Light Theme */
:root {
  --bg-color: #ffffff;
  --text-color: #000000;
  /* Add more as needed */
}

/* Dark Theme */
body.dark {
  --bg-color: #000000;
  --text-color: #ffffff;
}

Apply the Custom Properties

Use the defined custom properties to style elements throughout your site:

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

Create a Stylish Theme Switcher Toggle

Add the following HTML and CSS to create an attractive toggle switcher:

HTML:

<label class="switch">
  <input type="checkbox" id="theme-switcher">
  <span class="slider round"></span>
</label>

CSS:

.switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
}
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
.switch input:checked + .slider {
  background-color: #476173;
}
.switch input:checked + .slider:before {
  transform: translateX(20px);
  background-color: transparent;
  border-radius: 50%;
  border-top-color: transparent;
  border-left-color: transparent;
  border-right-color: transparent;
  box-shadow: inset -5px -3px 0 #d8e9ef;
}
.switch .slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #7bb9f5;
  transition: 0.4s;
  border-radius: 20px;
  box-shadow: 0 0 0.25em rgba(67, 71, 85, 0.27), 0.2px 0.2em 24px 0 rgba(1, 29, 77, 0.15);
}
.switch .slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: yellow;
  transition: 0.4s;
  border-radius: 50%;
  text-align: center;
  line-height: 16px;
}

Tip: Check out the demo on Codepen for SCSS code instead of plain CSS.

Add JavaScript for Theme Switching and Save Preferences

Incorporate JavaScript to manage the theme switching and save preferences using localStorage:

document.addEventListener('DOMContentLoaded', function() {
  const themeSwitcher = document.getElementById('theme-switcher');

  // Load saved theme preference
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme === 'dark') {
    document.body.classList.add('dark');
    themeSwitcher.checked = true;
  }

  // Detect OS preference if no saved preference
  else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
    document.body.classList.add('dark');
    themeSwitcher.checked = true;
  }

  // Handle toggle switch
  themeSwitcher.addEventListener('change', function() {
    document.body.classList.toggle('dark');
    localStorage.setItem('theme', this.checked ? 'dark' : 'light');
  });
});

Conclusion

Creating a light/dark theme switcher is more than just a visual enhancement; it’s a step towards building an accessible and user-centric web experience. By using CSS custom properties, a stylish toggle switcher, and leveraging localStorage to remember user preferences, you can craft a seamless and customized user experience that resonates with your audience.

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *