Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Implement dark mode and theme switching in a SvelteKit app using Tailwind CSS.

  1. User

    Implement dark mode and theme switching in a SvelteKit app using Tailwind CSS.

  2. Gemini Assistant

    Analyzing Dark Mode Implementation

    I'm currently focused on the core objective: enabling dark mode and theme switching in SvelteKit using Tailwind CSS. I'm exploring the fundamental requirements and potential challenges inherent in this integration, and considering user expectations. Next, I'll dive into the setup and configuration process.

    Outlining Theme Switching Logic

    I've been mapping out the technical pieces for theme switching. I'm focusing on SvelteKit, Tailwind CSS, and using localStorage for persistence. My strategy involves a Tailwind configuration to trigger dark mode classes, a store for theme state, and a vital script injection in app.html to prevent FOUC during SSR. A UI toggle will complete the user experience.

    Refining the Implementation Steps

    I'm now iterating on the core steps. I've got to ensure the dark mode class is applied to the HTML element. I also need to make sure the Svelte store accurately manages the theme state, providing a smooth user experience. This goes hand in hand with how I'll create the necessary toggle UI component to integrate with the store for control. Finally, I need to consider using selector to be backward compatible in Tailwind.

    Revising Code & Structure

    I'm now refining the code snippets and the guide's structure. I've realized the need for a store that handles the logic, rather than just subscribing directly to changes. Also, I'm making sure to use browser checks to prevent SSR issues with localStorage. I have to ensure onMount before accessing window. I'm focusing on the guide's clarity, including prerequisites and each core step: Config, app.html, Theme Store, and the toggle UI component with styles. I'm also including clear examples of how styles change in the guide.

    Crafting the Final Guide

    I'm now putting the finishing touches on the tutorial. I've written the Config, app.html, Store, and Component sections, including code snippets and explanations. I've also incorporated the best practices I identified, ensuring the toggle respects system preferences and prevents FOUC. The button will have an aria-label for accessibility. Finally, I'll add formatting and clarify the rationale behind the crucial script injection. Also, I've decided to keep it simple with a Light/Dark toggle, using the system preference as the initial state.

    Producing the Complete Output

    I'm now generating the tutorial output, pulling together all the components and explanations. I'm focusing on ensuring everything flows logically and is easy to follow, making sure the user has a great experience. I'm checking that the code snippets are complete, that the text is clear, and that all explanations are accurate. I'm also preparing a simple README to describe how to get the most from this tutorial.

    Here is a comprehensive guide to implementing dark mode in SvelteKit with Tailwind CSS.

    This approach solves the common "Flash of Incorrect Theme" (FOIT) issue inherent in Server-Side Rendering (SSR) frameworks by injecting a script before the app loads.

    Prerequisites

    • A SvelteKit project set up.
    • Tailwind CSS installed and configured.

    Step 1: Configure Tailwind

    Open your tailwind.config.js (or .ts) file. You need to tell Tailwind to toggle dark mode manually via a specific CSS class (usually .dark) rather than relying solely on the operating system preference.

    // tailwind.config.js
    /** @type {import('tailwindcss').Config} */
    export default {
      content: ['./src/**/*.{html,js,svelte,ts}'],
      // This is the key line:
      darkMode: 'class', 
      theme: {
        extend: {},
      },
      plugins: [],
    }
    

    Step 2: Prevent the "Flash" (app.html)

    Since SvelteKit renders HTML on the server, we cannot wait for a Svelte component to mount to check the user's theme preference. We must put a small blocking script in the <head> to check localStorage or system preferences immediately.

    Open src/app.html and add this script inside the <head> tag:

    <!-- src/app.html -->
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8" />
    		<link rel="icon" href="%sveltekit.assets%/favicon.png" />
    		<meta name="viewport" content="width=device-width" />
    		%sveltekit.head%
    
    		<!-- Add this script to handle initial theme load -->
    		<script>
    			if (
    				localStorage.getItem('color-theme') === 'dark' ||
    				(!('color-theme' in localStorage) &&
    					window.matchMedia('(prefers-color-scheme: dark)').matches)
    			) {
    				document.documentElement.classList.add('dark');
    			} else {
    				document.documentElement.classList.remove('dark');
    			}
    		</script>
    	</head>
    	<body data-sveltekit-preload-data="hover">
    		<div style="display: contents">%sveltekit.body%</div>
    	</body>
    </html>
    

    Step 3: Create a Theme Store

    We need a store to manage the state so the toggle button stays in sync across the application.

    Create src/stores/theme.js (or .ts):

    // src/stores/theme.js
    import { writable } from 'svelte/store';
    import { browser } from '$app/environment';
    
    // Default to 'light' if running on server to prevent errors
    // The script in app.html handles the visual part on the client
    const defaultValue = 'light';
    
    const initialValue = browser
    	? window.localStorage.getItem('color-theme') ?? 
          (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
    	: defaultValue;
    
    export const theme = writable(initialValue);
    
    theme.subscribe((value) => {
    	if (browser) {
    		window.localStorage.setItem('color-theme', value);
    		if (value === 'dark') {
    			document.documentElement.classList.add('dark');
    		} else {
    			document.documentElement.classList.remove('dark');
    		}
    	}
    });
    
    export { theme as default };
    

    Step 4: Create a Toggle Component

    Create a component that allows the user to switch the store value. Create src/lib/components/ThemeToggle.svelte:

    <!-- src/lib/components/ThemeToggle.svelte -->
    <script>
    	import { theme } from '../../stores/theme';
    	
    	function toggleTheme() {
    		$theme = $theme === 'dark' ? 'light' : 'dark';
    	}
    </script>
    
    <button
    	on:click={toggleTheme}
    	class="p-2 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-400"
    	aria-label="Toggle Dark Mode"
    >
    	<!-- Simple SVG Icons -->
    	{#if $theme === 'dark'}
    		<!-- Sun Icon -->
    		<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
    			<path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z" />
    		</svg>
    	{:else}
    		<!-- Moon Icon -->
    		<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
    			<path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z" />
    		</svg>
    	{/if}
    </button>
    

    Step 5: Apply Styles and Usage

    Now you can use the component in your layout and apply specific Tailwind classes.

    1. Update your Layout (src/routes/+layout.svelte):

    <script>
      import '../app.css'; // Ensure tailwind directives are imported
      import ThemeToggle from '$lib/components/ThemeToggle.svelte';
    </script>
    
    <!-- 
      Apply background/text colors to the main wrapper.
      These classes change automatically based on the 'dark' class on <html> 
    -->
    <div class="min-h-screen bg-white text-gray-900 dark:bg-gray-900 dark:text-white transition-colors duration-300">
      
      <header class="p-4 flex justify-between items-center border-b border-gray-200 dark:border-gray-700">
        <h1 class="text-xl font-bold">My App</h1>
        <ThemeToggle />
      </header>
      
      <main class="p-4">
        <slot />
      </main>
    
    </div>
    

    2. Styling individual elements: Anywhere in your app, simple use the dark: prefix:

    <div class="bg-blue-500 dark:bg-red-500">
      I am blue in light mode, and red in dark mode.
    </div>
    

    Summary of Logic Flow

    1. User loads app within browser.
    2. app.html runs immediately. It checks if the user has visited before (localStorage) or checks their System OS Preference (matchMedia). It adds class="dark" to the <html> tag if needed.
    3. SvelteKit hydrates. The theme.js store initializes, reads the current state from localStorage/DOM, and syncs up.
    4. User clicks the toggle. Store updates. Store subscription updates localStorage and toggles the CSS class. Tailwind re-renders styles.

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