Implementing Theme Management
I’m proposing an implementation plan that utilizes Tailwind's "class" strategy to toggle between "light," "dark," and potentially "system" themes. We'll use a ThemeStore in Svelte to manage the theme and save it in localStorage, checking for the "browser" from $app/environment due to SSR.
First, I'll mention installing Tailwind CSS in SvelteKit. We'll configure the tailwind.config to set darkMode as 'class'. In src/app.html, I’ll set the HTML language and include an inline script to sync the theme before hydration. This script will handle persistent theme settings while keeping it lightweight.Setting Up the Theme Store
I'm creating a theme store in src/lib/stores/theme.ts or .js using Svelte's writable store along with the browser check.
First, I’ll define a type called Theme for 'light', 'dark', and 'system'. The getInitialTheme function checks if we're in a browser environment. If not, it defaults to 'system'. If a theme is stored in localStorage, it uses that.
I'll export a writable store, and create a subscribe function that updates the document root's class based on the current theme, managing the theme in localStorage too. It’s also important to handle system theme change events.Enhancing the Theme Store
I can enhance the theme store by checking if we're in the browser and if the window has matchMedia. If so, I’ll set up an event listener for changes in the color scheme to re-apply the theme.
Svelte store subscriptions don't easily handle cleanup, but I might use a start/stop function instead of creating a more complex store.
In a component like src/lib/components/ThemeToggle.svelte, I can use buttons to toggle the theme, importing the theme from my store. For the UI, I'll suggest using Tailwind classes for styling and demonstrate integrating the ThemeToggle in layout.svelte. It’s good to remember customizing Tailwind’s config with custom colors or DaisyUI while keeping theming client-side focused.Preparing Theme Instructions
I see some potential issues: localStorage isn't accessible in SSR or in app.html. The inline script can only use plain JS without imports.
For the final instructions, we’ll take a step-by-step approach. I should start by mentioning how to set up a default SvelteKit app with Tailwind, using something like npm create svelte@latest my-app and choosing skeleton, TypeScript, and Tailwind.
Next, I’ll instruct on how to set darkMode: 'class', and provide example components. Customizing tailwind.config with a safelist for the dark class could be mentioned but isn't essential. I'll structure it into an overview, configuration, and an optional theme script in app.html for pre-hydration.Creating a Theme Switching System
I’m planning to create a Svelte store for theme management. This will involve building a ThemeToggle component and utilizing Tailwind's dark classes across the UI. I could handle "system" theme changes with media query updates, but since the focus is on dark mode, I’ll start with just 'light' and 'dark'.
In the Tailwind config, I’ll set darkMode: 'class', and provide minimal but clear code examples. The src/lib/stores/theme.ts file will implement a writable store to manage the theme state using localStorage for persistence.
Additionally, I’ll ensure to include an inline script in app.html for matching the preferred color scheme before hydration to prevent a flash of light. The ThemeToggle component will allow users to switch between themes easily, while also incorporating relevant Tailwind classes for consistent styling.Exploring Theming Options
I should also consider an alternative approach for theming using cookies and hooking into SvelteKit's handle(). However, that's a more advanced technique, so I’ll mention it only as a note.
The main focus is implementing dark mode and theme switching in a SvelteKit app using Tailwind CSS. We don't need to include full offline detection, but demonstrating a persistent theme using localStorage is important. I'll provide a clear answer, assuming minimal knowledge of SvelteKit environment by specifying where to place the code effectively. Below is a minimal but complete way to add dark mode + theme switching to a SvelteKit app that uses Tailwind.
You’ll get:
- Tailwind configured for dark mode
- A global HTML class (
dark) that Tailwind uses
- A store to manage the theme and persist it in
localStorage
- A toggle component to switch between light/dark
1. Configure Tailwind for class-based dark mode
In tailwind.config.cjs or tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: 'class', // <- important
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: []
};
This tells Tailwind to use a .dark class at the root (instead of prefers-color-scheme media queries).
2. Pre-apply the theme before Svelte hydrates (optional but recommended)
To avoid a “flash” of the wrong theme, set the dark class on <html> as early as possible.
Edit 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%
<!-- Tiny inline script to apply dark/light before Svelte loads -->
<script>
(function () {
const storageKey = 'theme';
const classNameDark = 'dark';
try {
const stored = localStorage.getItem(storageKey);
const prefersDark =
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = stored || (prefersDark ? 'dark' : 'light');
if (theme === 'dark') {
document.documentElement.classList.add(classNameDark);
} else {
document.documentElement.classList.remove(classNameDark);
}
} catch (e) {
// fail silently – just don't break rendering
}
})();
</script>
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
Now the correct theme is applied before your Svelte code runs.
3. Create a theme store
Create src/lib/stores/theme.ts (or .js):
// src/lib/stores/theme.ts
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
type Theme = 'light' | 'dark';
const STORAGE_KEY = 'theme';
function getInitialTheme(): Theme {
if (!browser) return 'light';
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'light' || stored === 'dark') return stored;
const prefersDark =
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
return prefersDark ? 'dark' : 'light';
}
function applyTheme(theme: Theme) {
if (!browser) return;
const root = document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
localStorage.setItem(STORAGE_KEY, theme);
}
function createThemeStore() {
const initial = getInitialTheme();
const { subscribe, set, update } = writable<Theme>(initial);
// Apply immediately on first run in the browser
if (browser) applyTheme(initial);
// Whenever the store changes, sync it to DOM + localStorage
subscribe((value) => {
applyTheme(value);
});
return {
subscribe,
set,
toggle: () => update((t) => (t === 'dark' ? 'light' : 'dark'))
};
}
export const theme = createThemeStore();
This store:
- Determines an initial theme (localStorage → system preference → default light)
- Keeps
<html>’s classList and localStorage in sync
- Exposes
theme.toggle() for easy toggling
4. Make a simple theme toggle component
Create src/lib/components/ThemeToggle.svelte:
<script lang="ts">
import { theme } from '$lib/stores/theme';
</script>
<button
type="button"
class="inline-flex items-center gap-2 rounded-full border px-3 py-1 text-sm
bg-white text-slate-900 hover:bg-slate-100
dark:bg-slate-800 dark:text-slate-100 dark:hover:bg-slate-700
transition-colors"
on:click={() => theme.toggle()}
>
{#if $theme === 'dark'}
<span>☀</span>
<span>Light mode</span>
{:else}
<span>🌙</span>
<span>Dark mode</span>
{/if}
</button>
Svelte automatically subscribes to the store when you use $theme.
5. Wire it into your layout
In src/routes/+layout.svelte:
<script lang="ts">
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
</script>
<div
class="min-h-screen
bg-white text-slate-900
dark:bg-slate-900 dark:text-slate-50
transition-colors"
>
<header class="flex justify-end p-4">
<ThemeToggle />
</header>
<main class="p-4">
<slot />
</main>
</div>
Now any dark: classes inside your app will respond to the global .dark class on <html>.
6. Use Tailwind’s dark: utilities in your components
Example:
<div class="p-4 rounded-lg bg-slate-100 text-slate-900 dark:bg-slate-800 dark:text-slate-100">
This box follows the current theme.
</div>
When the user clicks the toggle:
- The store updates
<html> gets .dark added/removed
- Tailwind’s
dark: utilities update styles
- Choice is persisted in
localStorage and restored on next visit
If you’d like, I can extend this to also support a third “System” option (light / dark / system) that tracks the OS theme dynamically.