Skip to content
WebJs
Menu

Adding dark mode to your site.

The theme init installs defines every token twice: once under :root for light mode and once under .dark for dark mode. A dark custom variant matches anything inside a .dark element, so a component's dark: utilities follow the same switch.

styles/globals.css
@custom-variant dark (&:is(.dark *));

:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  /* ... */
}

.dark {
  --background: oklch(0.145 0 0);
  --foreground: oklch(0.985 0 0);
  /* ... */
}

So dark mode is one class on the <html> element. The page needs a script that sets the class before it paints, and a control that changes it.

An app made with webjs create already has both: the root layout carries the theme script, and components/theme-toggle.ts cycles between system, light and dark. Follow the steps below for an app that does not.

Add dark mode

Add the theme script

Add an inline script to the root layout. It reads the saved choice, falls back to the operating system's preference, and sets the class before the first paint, so a reader who chose dark never sees the light palette flash. It also follows the system setting when it changes while the page is open.

app/layout.ts
import { html, cspNonce } from '@webjsdev/core';
import type { LayoutProps } from '@webjsdev/core';

export default function RootLayout({ children }: LayoutProps) {
  return html`
    <script nonce=${cspNonce()}>
      (function () {
        try {
          var mq = window.matchMedia('(prefers-color-scheme: dark)');
          function apply() {
            var t = null;
            try { t = localStorage.getItem('webjs_theme'); } catch (_) {}
            document.documentElement.classList.toggle(
              'dark', t === 'dark' || (t !== 'light' && mq.matches),
            );
          }
          apply();
          mq.addEventListener('change', apply);
        } catch (_) {}
      })();
    </script>
    <meta name="color-scheme" content="light dark">
    ${children}
  `;
}

The script must stay inline and come first in the root layout, since a module would run after the first paint. cspNonce() returns the request's nonce when the app turns on a Content Security Policy, and an empty string otherwise.

Add a mode toggle

Place a mode toggle on your site to toggle between light and dark mode. This one is a dropdown menu with the three choices. It saves an explicit choice, forgets it for System, and sets the class the same way the script does.

components/mode-toggle.ts
import { WebComponent, html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import '#components/ui/dropdown-menu.ts';

type Theme = 'light' | 'dark' | 'system';

export class ModeToggle extends WebComponent {
  setTheme(theme: Theme) {
    try {
      if (theme === 'system') localStorage.removeItem('webjs_theme');
      else localStorage.setItem('webjs_theme', theme);
    } catch {}
    const dark = theme === 'dark'
      || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
    document.documentElement.classList.toggle('dark', dark);
  }

  render() {
    return html`
      <ui-dropdown-menu @ui-item-select=${(e: CustomEvent<{ value: Theme }>) => this.setTheme(e.detail.value)}>
        <ui-dropdown-menu-trigger>
          <button class=${cn(buttonClass({ variant: 'outline', size: 'icon' }), 'relative')}>
            <svg class="size-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2m-7.07-14.07 1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/></svg>
            <svg class="absolute size-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg>
            <span class="sr-only">Toggle theme</span>
          </button>
        </ui-dropdown-menu-trigger>
        <ui-dropdown-menu-content align="end">
          <ui-dropdown-menu-item value="light">Light</ui-dropdown-menu-item>
          <ui-dropdown-menu-item value="dark">Dark</ui-dropdown-menu-item>
          <ui-dropdown-menu-item value="system">System</ui-dropdown-menu-item>
        </ui-dropdown-menu-content>
      </ui-dropdown-menu>
    `;
  }
}

ModeToggle.register('mode-toggle');

Add the dropdown menu and the button to your project first:

npx @webjsdev/ui add dropdown-menu button

Then import the component from a page or layout and render its tag where the toggle belongs. Importing it is what registers the element in the browser.

import '#components/mode-toggle.ts';

html`<header>... <mode-toggle></mode-toggle></header>`

Without JavaScript

With JavaScript off the script never runs and nothing sets the class, so the page renders in light mode and the toggle does nothing. Everything else on the page still works, since the theme is only CSS.