Skip to content

Dark and Light theme toggle using CSS

Published:  at  πŸ•“ 03:30 PM
⏰ 2 min read

Switching between dark and light themes has become a popular feature in modern web design, offering users the flexibility to choose a visual style that best suits their preferences or environment. Implementing a theme toggle not only enhances accessibility but also improves user experience by reducing eye strain in low-light conditions and providing a visually appealing interface. With CSS and a small amount of JavaScript, you can easily add a dark and light mode toggle to your website. This guide will walk you through the steps to create a seamless theme switcher using CSS variables and simple scripting.

To implement a dark and light theme toggle for a website using CSS, you can use the following steps:

Table of Contents

Open Table of Contents

Start Coding your Dark Mode Switcher

Before diving into the code, it’s important to understand the benefits of implementing a dark mode switcher. This feature not only caters to user preferences but also enhances accessibility and comfort, especially in low-light environments. Let’s explore how to build a simple and effective dark mode toggle for your website.

1. Define Theme Styles in CSS

Create styles for both light and dark themes. Use CSS variables (--variable-name) to make switching easier.

/* Default (Light Theme) */
:root {
  --background-color: #ffffff;
  --text-color: #000000;
}

/* Dark Theme */
[data-theme="dark"] {
  --background-color: #000000;
  --text-color: #ffffff;
}

/* Apply Variables */
body {
  background-color: var(--background-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}

2. Add a Theme Toggle Button in HTML

Create a button for toggling between themes.

<button id="theme-toggle">Toggle Theme</button>

3. Write JavaScript for Theme Switching

Use JavaScript to toggle the theme by changing the data-theme attribute on the <html> element.

const toggleButton = document.getElementById('theme-toggle');
const currentTheme = localStorage.getItem('theme');

// Apply the saved theme (if any) on page load
if (currentTheme) {
  document.documentElement.setAttribute('data-theme', currentTheme);
}

// Toggle theme on button click
toggleButton.addEventListener('click', () => {
  const current = document.documentElement.getAttribute('data-theme');
  const newTheme = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', newTheme);

  // Save the new theme in localStorage
  localStorage.setItem('theme', newTheme);
});

4. Add Transition for Smooth Effects (Optional)

For a smooth user experience, ensure transitions are added in the CSS:

body {
  transition: background-color 0.3s ease, color 0.3s ease;
}

5. Test Your Implementation

  • Save your work and test the button.
  • The theme should toggle between light and dark modes and persist after page reloads (thanks to localStorage).

Further Reading