Skip to content
GitHub11 stars

Dark Mode

Adding dark mode to your site.

The theme's dark tokens apply under a .dark class. Put it on <html> to darken the whole app, or on any element to darken part of it: popups render in the top layer but stay inside that element, so they follow along.

Setup

Apply the saved theme before the page paints

Add a script to the <head> of App.razor. It runs before anything shows, so there's no flash of the wrong theme.

Components/App.razor
<head>
    ...
    <script>
        try {
            const dark = localStorage.theme === 'dark' ||
                (!('theme' in localStorage) && matchMedia('(prefers-color-scheme: dark)').matches);
            document.documentElement.classList.toggle('dark', dark);
        } catch (_) {}
    </script>
</head>

Add a toggle script

The theme lives on <html>, which a Blazor app doesn't render interactively, so a small module switches it. It also saves the choice; if storage is turned off, the toggle still works for the current page.

wwwroot/theme.js
export function toggleTheme() {
  const dark = !document.documentElement.classList.contains('dark');
  document.documentElement.classList.toggle('dark', dark);
  try {
    localStorage.theme = dark ? 'dark' : 'light';
  } catch {}
}

Add a mode toggle

Place a toggle on your site to switch between light and dark mode.

Components/Layout/ModeToggle.razor
@inject IJSRuntime JS
@using Blazix.Icons
@using Blazix.Icons.Lucide

<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Icon" @onclick="ToggleAsync">
    <Icon Data="LucideIcons.Sun" aria-hidden="true" class="hidden dark:block" />
    <Icon Data="LucideIcons.Moon" aria-hidden="true" class="dark:hidden" />
    <span class="sr-only">Toggle theme</span>
</Button>

@code {
    private IJSObjectReference? _module;

    private async Task ToggleAsync()
    {
        _module ??= await JS.InvokeAsync<IJSObjectReference>("import", "./theme.js");
        await _module.InvokeVoidAsync("toggleTheme");
    }
}