The user wants to implement dark mode and theme switching in a SvelteKit application using Tailwind CSS.
Key Requirements:
Framework: SvelteKit.
Styling: Tailwind CSS.
Feature: Dark mode and theme switching (Light/Dark/System).
Core Concepts/Steps:
Tailwind Configuration: Configure Tailwind to use the class strategy for dark mode (instead of media). This allows manual toggling via a class on a parent element (usually <html> or <body>).
State Management: Need a way to store the user's preference.
localStorage: To persist the choice across reloads.
Svelte Store: To manage the state within the app reactively.
Layout/HTML Setup: Apply the class (dark) to the <html> element.
Issue: SvelteKit insulates the <html> tag. We need to modify src/app.html? No, usually we manipulate it via hooks.client.ts or a layout script to avoid hydration mismatch (FOUC - Flash of Unstyled Content).
Best Practice: Use a script in app.html (inline) to set the class before the page renders to prevent the flash. Then sync it with a Svelte store.
Theme Toggle Component: Create a UI component to switch themes.
Implementation Details:
Tailwind Config:darkMode: 'class'.
Store: Create a writable store.
Root Layout (+layout.svelte): Subscribe to the store and update the DOM/localStorage.
Step-by-Step Plan:
Prerequisites: Assume SvelteKit and Tailwind are already set up (using @skeletonlabs/skeleton or just standard svelte-add/tailwindcss). I will assume a standard setup.
Tailwind Config: Update tailwind.config.js to enable class mode.
Theme Store: Create a TS/JS file to handle the logic.
Needs to check localStorage.
Needs to check window.matchMedia('(prefers-color-scheme: dark)') for system preference.
Needs to update the <html> class.
Handling the "Flash" (FOUC):
This is the trickiest part of SvelteKit dark mode.
Approach: Put a small blocking script inside <head> of src/app.html. This reads localStorage and sets the class immediately.
Alternative: Use onMount in layout, but this causes a flash. The inline script is better for UX.
Svelte Component:
Create a toggle or dropdown.
Use icons (Sun/Moon).
On click -> Update Store -> Update LocalStorage -> Update Class.
Refining the Approach (Modern SvelteKit):
Using mode-watcher is a very popular and robust library for this now. Should I suggest a library or vanilla implementation?
Vanilla: Better for understanding and zero dependencies.
Library: Easier.
Decision: I will provide the Vanilla Implementation first because it answers the prompt directly without assuming third-party lib usage, but I will mention mode-watcher as a pro-tip at the end.
Drafting the Vanilla Code:
Step 1: Tailwind Config
js
export default {
darkMode: 'class', // Important
// ...
}
Step 2: The Store (lib/stores/theme.ts)
Type: 'light' | 'dark' | 'system'.
Default: 'system'.
Step 3: The app.html Script
Needs to run before load.
Script: Check local storage, if not found check media query, add/remove 'dark' class.
Step 4: The Layout Logic (+layout.svelte)
Import store.
onMount: initialize store from localStorage (if not handled by app.html script, but app.html handles DOM, store handles JS state).
Watch store changes -> Update DOM + LocalStorage.
Revised "Best Practice" Vanilla Approach:
Writing inline scripts in app.html is a bit messy. A cleaner way in SvelteKit (without libraries) is:
Define a store.
In +layout.svelte (or +layout.ts), check localStorage.
However, server-side rendering makes this hard because localStorage doesn't exist on the server.
Therefore, the safest vanilla way to avoid hydration mismatch and flashing is:
The Inline Script: Put it in app.html. It's the only thing fast enough.
Let's structure the guide:
Setup Tailwind:darkMode: 'class'.
Theme Store: Create a simple store to manage state.
Prevent Flashing: Add a script to app.html.
Component: Create a switcher.
Integration: Add the component to the navbar/layout.
Let's write the code mentally:
Tailwind Config:darkMode: 'class'
Theme Store:
Needs to handle the update of the class on document.documentElement.
The Svelte Component:
Needs to toggle the store.
Store needs to update localStorage and document.documentElement.classList.
Alternative using mode-watcher (Mental Check):
If I use mode-watcher, it's just import { ModeWatcher } from 'mode-watcher' and <ModeWatcher /> in root layout. It handles everything.
Decision: I will stick to the manual implementation as the primary answer to ensure they learn the mechanics, but mention mode-watcher as a "Pro Tip". It demonstrates seniority and awareness of the ecosystem.
Detailed Steps for Manual Implementation:
Configure Tailwind:
Modify tailwind.config.js.
Manage State (Store):
Create src/lib/stores/themeStore.js.
Logic:
Get initial value? Can't on server. Assume 'system'.
Function setTheme(theme):
Update localStorage.
Update document.documentElement class.
Handle Initial Load (The "Flash" fix):
Modify src/app.html.
Add script in <head>.
Create Toggle Component:src/lib/components/ThemeToggle.svelte.
UI: Sun/Moon icons.
Logic: Switch between light/dark.
Usage:
Import in +layout.svelte.
Self-Correction during drafting:
Wait, if I put the logic in a store, but the initial HTML script sets the class, I need to make sure the store is synced with what the HTML script did when the app hydrates.
HTML Script sets class based on local storage.
Store initializes.
When Store initializes on client, it should read localStorage to set its initial value so the UI toggle (e.g., checkbox) is in the correct state.
Revised Store Logic:
The store holds the user's preference ('light', 'dark', 'system').
The actual applied class is derived from that.
Simpler approach for a tutorial: Just toggle between Light and Dark. System support adds complexity (listening to media query changes). I will include System support because it's standard nowadays.
Result: White flash on reload.
Solution: The inline script is the only way to do this 100% correctly in vanilla SSR SvelteKit.
Let's write the solution.
Here is a complete, step-by-step guide to implementing dark mode in a SvelteKit application using Tailwind CSS.
This approach uses the "Class Strategy" (manually toggling a class on the <html> element), which is the standard best practice for SvelteKit to avoid hydration mismatches and allow for user preference persistence.
Step 1: Configure Tailwind CSS
First, tell Tailwind to look for a dark class on the HTML element rather than relying solely on the operating system preference.
Open tailwind.config.js and add or update the darkMode setting:
javascript
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
// Use 'class' strategy for manual control
darkMode: 'class',
theme: {
extend: {}
},
plugins: []
};
Step 2: Prevent "Flash" on Page Load
The most common issue with server-rendered dark mode is the "Flash of Incorrect Content" (FOSC), where the page loads white for a split second before turning dark.
To prevent this, we need a small inline script in your main HTML file that runs before Svelte hydrates the page.
Open src/app.html and add the following <script> tag inside the <head>:
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, initial-scale=1" />
%sveltekit.head%
<!-- Add this script -->
<script>
// Immediately check localStorage to set the class before the page renders
if (localStorage.getItem('theme') === 'dark' ||
(!('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 way to manage the state globally so the toggle button knows if dark mode is active. We will create a Svelte store that syncs with localStorage.
Create a new file: src/lib/stores/theme.js.
javascript
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
// Helper to get the system preference
const getSystemPreference = () => {
if (!browser) return 'light'; // Default for server-side rendering
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
// 1. Initialize from localStorage if available, otherwise system preference
const initialValue = browser
? (localStorage.getItem('theme') || getSystemPreference())
: 'light';
const theme = writable(initialValue);
// 2. Subscribe to changes to update the DOM and localStorage
export default {
subscribe: theme.subscribe,
toggle: () => {
theme.update(current => {
const newTheme = current === 'dark' ? 'light' : 'dark';
if (browser) {
// Update LocalStorage
localStorage.setItem('theme', newTheme);
// Update the <html> class
if (newTheme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
return newTheme;
});
}
};
Step 4: Create the Theme Switcher Component
Create a component to toggle the theme. We'll use browser check to ensure we only render icons on the client to avoid hydration errors.
No Hydration Mismatch: The store is initialized with browser ? localStorage... : 'light'. This ensures the server renders a consistent output. The inline script in app.html ensures the user sees the correct theme immediately, even before the JS loads.
System Preference Fallback: The inline script in Step 2 and the store in Step 3 both respect prefers-color-scheme if the user hasn't explicitly picked a theme yet.
Clean Toggle: The CSS classes dark:bg-gray-800 etc., allow you to style everything strictly via Tailwind.
Pro Tip: Using mode-watcher
If you want a more robust, community-tested solution without writing the store logic yourself, you can install the mode-watcher package which is part of the Skeleton UI ecosystem but works standalone.
npm install @skeletonlabs/skeleton
Wrap your app in <ModeWatcher /> in your root layout.
However, the manual steps above are usually preferred for simple setups to avoid external dependencies.