Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro· GoogleHugging Face LMArena Human Preference 140K

how can i easily implement a dark-light css theme toggle switch for use in html5?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-opus-4-20250514-thinking-16k’s answer.
  1. User

    how can i easily implement a dark-light css theme toggle switch for use in html5?

  2. Gemini Assistant

    Of course! Implementing a dark/light theme toggle is a fantastic feature for modern websites. Here’s a guide that shows you the easiest and most modern way to do it using CSS Custom Properties (Variables) and a little bit of JavaScript for the logic and saving the user's preference.

    The Core Concept

    We will use a data attribute on the <html> element to control the theme.

    • Light Theme (Default): <html data-theme="light">
    • Dark Theme: <html data-theme="dark">

    Our CSS will define colors using variables. Then, we'll simply change the values of those variables when the data-theme attribute is set to "dark". JavaScript will handle toggling the attribute and saving the user's choice in localStorage.


    Step 1: The HTML (index.html)

    Create a simple HTML structure. All you need is a button to act as our toggle switch.

    <!DOCTYPE html>
    <html lang="en" data-theme="light"> <!-- Default theme is light -->
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dark/Light Toggle</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
    
        <header>
            <h1>Theme Toggler</h1>
            <button id="theme-toggle">Switch Theme</button>
        </header>
    
        <main>
            <h2>Welcome to the Site</h2>
            <p>This is some sample text. Click the button in the header to switch between light and dark themes!</p>
            <a href="#">This is a sample link.</a>
        </main>
    
        <script src="script.js"></script>
    </body>
    </html>
    

    Step 2: The CSS (style.css)

    This is where the magic happens. We use CSS Custom Properties (variables) to make the theme switch incredibly simple and maintainable.

    /* 1. Define color variables for the light theme */
    :root {
      --background-color: #f0f0f0;
      --text-color: #222;
      --primary-color: #007bff;
      --card-bg-color: #ffffff;
    }
    
    /* 2. Define color variables for the dark theme */
    [data-theme="dark"] {
      --background-color: #121212;
      --text-color: #f0f0f0;
      --primary-color: #bb86fc;
      --card-bg-color: #1e1e1e;
    }
    
    /* 3. Apply the variables and add a smooth transition */
    body {
      background-color: var(--background-color);
      color: var(--text-color);
      font-family: sans-serif;
      transition: background-color 0.3s, color 0.3s;
    }
    
    /* General styling for demonstration */
    h1, h2, p, a {
      color: var(--text-color);
    }
    
    a {
      color: var(--primary-color);
    }
    
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem 2rem;
      background-color: var(--card-bg-color);
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      border-radius: 8px;
      margin: 1rem;
    }
    
    main {
      padding: 2rem;
      margin: 1rem;
      background-color: var(--card-bg-color);
      border-radius: 8px;
    }
    
    button {
      padding: 0.5rem 1rem;
      border: 1px solid var(--primary-color);
      background-color: transparent;
      color: var(--primary-color);
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s, color 0.3s;
    }
    
    button:hover {
      background-color: var(--primary-color);
      color: var(--card-bg-color);
    }
    

    Step 3: The JavaScript (script.js)

    This script will handle three things:

    1. Toggle the Theme: Switch the data-theme attribute on click.
    2. Save Preference: Store the user's choice in localStorage.
    3. Load Preference: Check for a saved theme or the user's OS preference when the page loads.
    document.addEventListener('DOMContentLoaded', () => {
        const themeToggle = document.getElementById('theme-toggle');
        const currentTheme = localStorage.getItem('theme');
    
        // Function to set the theme
        const setTheme = (theme) => {
            document.documentElement.setAttribute('data-theme', theme);
            localStorage.setItem('theme', theme);
            // Optional: Change button text based on theme
            if (theme === 'dark') {
                themeToggle.textContent = 'Switch to Light';
            } else {
                themeToggle.textContent = 'Switch to Dark';
            }
        };
    
        // 1. Check for a saved theme in localStorage
        if (currentTheme) {
            setTheme(currentTheme);
        } else {
            // 2. If no saved theme, check for the user's OS preference
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            if (prefersDark) {
                setTheme('dark');
            } else {
                setTheme('light'); // Default to light if no preference
            }
        }
    
        // Event listener for the toggle button
        themeToggle.addEventListener('click', () => {
            const theme = document.documentElement.getAttribute('data-theme');
            if (theme === 'dark') {
                setTheme('light');
            } else {
                setTheme('dark');
            }
        });
    });
    

    Best Practice: Avoiding the "Flash"

    Sometimes, you might see a "flash of the light theme" before the JavaScript loads and applies the dark theme. To fix this, you can add a tiny, inline script to the <head> of your HTML file.

    Replace the <head> in your index.html with this:

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dark/Light Toggle</title>
        
        <!-- This script runs before the page is rendered -->
        <script>
          (function() {
            const theme = localStorage.getItem('theme');
            if (theme) {
              document.documentElement.setAttribute('data-theme', theme);
            } else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
              document.documentElement.setAttribute('data-theme', 'dark');
            }
            // The default is 'light', so no 'else' is needed.
          })();
        </script>
        
        <link rel="stylesheet" href="style.css">
    </head>
    

    This mini-script runs instantly, setting the data-theme attribute before the browser even starts to paint the page, eliminating any flash. Your main script.js will still handle the button click logic.

    Going Further: Using an Icon (SVG)

    Using a sun/moon icon is a popular and intuitive UI pattern.

    1. Update your HTML button:

    <!-- Replace the old button with this one -->
    <button id="theme-toggle" aria-label="Toggle theme">
        <svg class="sun" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.25a.75.75 0 0 1 .75.75v2.25a.75.75 0 0 1-1.5 0V3a.75.75 0 0 1 .75-.75ZM7.5 12a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0Zm12.75 0a.75.75 0 0 1-.75.75h-2.25a.75.75 0 0 1 0-1.5h2.25a.75.75 0 0 1 .75.75ZM4.5 12a.75.75 0 0 1-.75.75H1.5a.75.75 0 0 1 0-1.5h2.25a.75.75 0 0 1 .75.75ZM12 19.5a.75.75 0 0 1 .75.75v2.25a.75.75 0 0 1-1.5 0V20.25a.75.75 0 0 1 .75-.75ZM17.25 6.75a.75.75 0 0 1 0 1.06l-1.591 1.591a.75.75 0 1 1-1.06-1.06l1.591-1.591a.75.75 0 0 1 1.06 0ZM8.341 15.659a.75.75 0 0 1 1.06 0l1.591 1.591a.75.75 0 0 1-1.06 1.06l-1.591-1.591a.75.75 0 0 1 0-1.06ZM18.311 17.25a.75.75 0 0 1-1.06 1.06l-1.591-1.591a.75.75 0 1 1 1.06-1.06l1.591 1.591ZM6.75 8.341a.75.75 0 0 1 1.06 0l1.591 1.591a.75.75 0 0 1-1.06 1.06L6.75 9.401a.75.75 0 0 1 0-1.06Z"/></svg>
        <svg class="moon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path fill-rule="evenodd" d="M9.528 1.718a.75.75 0 0 1 .162.819A8.97 8.97 0 0 0 9 6a9 9 0 0 0 9 9 8.97 8.97 0 0 0 3.463-.69a.75.75 0 0 1 .981.981A10.503 10.503 0 0 1 12 22.5C6.201 22.5 1.5 17.799 1.5 12A10.503 10.503 0 0 1 2.69 6.538a.75.75 0 0 1 .819-.162Z" clip-rule="evenodd"/></svg>
    </button>
    

    2. Add CSS to hide/show the correct icon:

    /* Add this to your style.css */
    #theme-toggle svg {
      width: 24px;
      height: 24px;
    }
    
    #theme-toggle .moon { display: none; }
    #theme-toggle .sun { display: block; }
    
    [data-theme="dark"] #theme-toggle .moon { display: block; }
    [data-theme="dark"] #theme-toggle .sun { display: none; }
    

    Now you have a fully functional, modern, and efficient dark/light theme toggle

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.