AI Bootstrap Logo
Bootstrap Questions & Answers Part of the Q&A Network

How do I implement dark mode using data-bs-theme with persistence?

Asked on Jul 30, 2025

Answer

To implement a dark mode using Bootstrap's `data-bs-theme` attribute with persistence, you can use local storage to save the user's theme preference. Here's a simple example to get you started.
<!-- BEGIN COPY / PASTE -->
        <div id="themeToggle" class="container" data-bs-theme="light">
            <button class="btn btn-primary" onclick="toggleTheme()">Toggle Theme</button>
        </div>

        <script>
            // Check for saved theme in local storage
            const savedTheme = localStorage.getItem('theme');
            const themeToggle = document.getElementById('themeToggle');

            if (savedTheme) {
                themeToggle.setAttribute('data-bs-theme', savedTheme);
            }

            function toggleTheme() {
                const currentTheme = themeToggle.getAttribute('data-bs-theme');
                const newTheme = currentTheme === 'light' ? 'dark' : 'light';
                themeToggle.setAttribute('data-bs-theme', newTheme);
                localStorage.setItem('theme', newTheme);
            }
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • This example uses a button to toggle between light and dark themes.
  • The `data-bs-theme` attribute is used to apply the theme to the container.
  • Local storage is used to save the user's theme preference, ensuring persistence across page reloads.
  • The script checks for a saved theme on page load and applies it if available.
✅ Answered with Bootstrap 5 best practices.
← Back to All Questions