In this post I will show you how to add darkmode to your website
First we need to add a component called DarkModeSwitcher.svelte
In this component you need to use this code
<script>
import { onMount } from 'svelte';
import { darkModeState } from './darkModeState.svelte';
function toggleDarkmode() {
darkModeState.state = !darkModeState.state;
const darkMode = document.cookie.includes('darkmode=true');
document.cookie = `darkmode=${!darkMode};path=/`;
document.body.classList.toggle('dark');
}
onMount(() => {
if (document.cookie.includes('darkmode')) {
darkModeState.state = document.cookie.includes('darkmode=true');
} else {
const darkMode =
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (darkMode) {
toggleDarkmode();
}
}
});
</script>
<label
class="fixed right-0 bottom-0 z-10 m-8 cursor-pointer items-center rounded-lg bg-zinc-200 p-4 text-black dark:bg-black dark:text-white"
>
<input type="checkbox" class="sr-only" onclick={toggleDarkmode} checked={darkModeState.state} />
<div>{darkModeState.state ? '☀️' : '🌙'}</div>
</label>
After that you need a component called darkModeState.svelte.ts
In that file you need that code
export const darkModeState = $state({
state: false
});
Now the almost last step is creating a hooks.server.ts in the src folder.
In the hooks server ts you need to use this code
import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
const darkMode: Handle = async ({ event, resolve }) => {
const darkModeCookie = event.cookies.get('darkmode') === 'true';
const response = await resolve(event, {
transformPageChunk: ({ html }) => html.replace('%darkmode%', darkModeCookie ? 'dark' : '')
});
return response;
};
export const handle = sequence(darkMode);
The last step now is to add a few lines to your app.css *When using the latest version of TailwindCSS (v4) you need to use a app.css instead of a tailwind.config.js`
So that you can use the dark mode class in your code you need to add this to your app.css
@custom-variant dark (&:where(.dark, .dark *));
Optional you can add these few lines so that it will automaticly change all the styles when toggling the dark mode
@layer base {
body {
@apply dark:bg-black bg-white text-black dark:text-white;
}
}
So that the dark mode system will work you only need to add class="%darkmode%" to the body in your app.html
When setting the background color or text color you should never use pure black or white because then the contrast will be too big
This code was inspired by fabian9799's dark mode snippet: https://snippets.fabian9799.cloud/snippet/sveltekit-darkmode