Back to all snippets
Library/Tailwind CSS/Dark Mode Toggle with localStorage
htmlintermediatedark-modeaccessibilityjavascriptlocalStorageui

How to implement Dark Mode Toggle with localStorage in Html

Implement dark mode toggle with persistent localStorage state using Tailwind CSS

Quick Answer

Store the theme preference in localStorage, toggle the dark class on the <html> element, and use Tailwind's dark: prefix on colour classes — the browser remembers the choice on reload.

Code Snippet

1<html id="html" class="">
2<head>
3  <script>
4    // Check localStorage or system preference on page load
5    const savedTheme = localStorage.getItem('theme');
6    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
7    
8    if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
9      document.documentElement.classList.add('dark');
10    }
11  </script>
12  <style>
13    /* Tailwind CSS is assumed to be imported */
14  </style>
15</head>
16<body class="bg-white dark:bg-slate-950 text-slate-900 dark:text-slate-50 transition-colors">
17  <header class="border-b border-slate-200 dark:border-slate-800">
18    <div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
19      <h1 class="text-2xl font-bold">My App</h1>
20      <button id="themeToggle" class="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors">
21        <svg id="sunIcon" class="w-5 h-5 hidden dark:block"><path fill="currentColor" d="M12 18a6 6 0 100-12 6 6 0 000 12zM12 2v4m0 8v4M4.22 4.22l2.83 2.83m4 4l2.83 2.83M2 12h4m8 0h4m-13.78 7.78l2.83-2.83m4-4l2.83-2.83"/></svg>
22        <svg id="moonIcon" class="w-5 h-5 block dark:hidden"><path fill="currentColor" d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
23      </button>
24    </div>
25  </header>
26  <main class="max-w-6xl mx-auto px-4 py-12">
27    <div class="bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg p-8">
28      <h2 class="text-xl font-semibold mb-4">Dark Mode Example</h2>
29      <p class="text-slate-600 dark:text-slate-400">Click the toggle in the header to switch themes. Your preference is saved.</p>
30    </div>
31  </main>
32
33  <script>
34    const themeToggle = document.getElementById('themeToggle');
35    
36    themeToggle.addEventListener('click', () => {
37      const isDark = document.documentElement.classList.toggle('dark');
38      localStorage.setItem('theme', isDark ? 'dark' : 'light');
39    });
40  </script>
41</body>
42</html>

What is Dark Mode Toggle with localStorage?

Dark mode is now table stakes for modern web apps. This pattern uses Tailwind's dark: variant prefix alongside JavaScript to toggle a dark class on the <html> element, with localStorage ensuring the user's preference persists across sessions. It's accessible, lightweight, and works without additional libraries.

How It Works

  1. 1JavaScript checks localStorage for a saved 'theme' preference and applies the 'dark' class to <html>
  2. 2A toggle button switches between light and dark, updating localStorage and the DOM in real time
  3. 3Tailwind's dark: prefix automatically applies colours when the dark class is present on the root element
  4. 4Optional: detect system preference with `window.matchMedia('(prefers-color-scheme: dark)')`

Common Use Cases

  • SaaS dashboards - Let users toggle between light and dark themes
  • Content sites - Reduce eye strain with a dark mode option
  • Developer tools - Coding-focused apps almost always include dark mode
  • Accessibility - Dark mode is essential for users with light sensitivity

Key Benefits

  • Respects user preference and persists across sessions
  • Works with Tailwind's built-in dark: utilities
  • No external dependencies — pure HTML, CSS, and vanilla JS
  • Detects system preference as a fallback

Common Mistakes to Avoid

  • Using CSS @media (prefers-color-scheme) alone — it only detects system preference, not user overrides. Use localStorage + JS for persistent user choice.
  • Toggling a class on the wrong element — the dark class must be on <html> for Tailwind dark: variants to work globally.
  • Not persisting to localStorage — without saving the preference, the page reverts to system preference on reload.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more html examples

Frequently Asked Questions

How do I detect the user's system dark mode preference?

Use `window.matchMedia('(prefers-color-scheme: dark)').matches` to check if their OS is set to dark mode. On first visit, use this as the default unless they've already toggled manually.

Can I use Tailwind dark mode without JavaScript?

Yes, with CSS media queries: `@media (prefers-color-scheme: dark) { ... }`. But user-initiated toggles require JavaScript and localStorage to persist across page loads.

About This Html Code Snippet

This free html code snippet for dark mode toggle with localstorage is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement dark mode toggle with localstorage quickly and correctly.

All snippets in the Snippetly library follow html best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses html.

Tags: dark-mode, accessibility, javascript, localStorage, ui  | Language: html  | Difficulty: intermediate  | Category: Tailwind CSS

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.