Guide

Theme

What @samline/theme does, how a theme is chosen, applied before the first paint, remembered and kept in sync with the system and other tabs.

@samline/theme manages light, dark and system themes, or any themes you name. Load it in <head> and the stored theme is on the page before it paints, so a dark page never flashes light. Buttons, radios and selects with data-theme-* attributes switch it without code.

<script src="https://cdn.jsdelivr.net/npm/@samline/theme@1.1.0/dist/browser/theme.global.js"></script>

<button type="button" data-theme-toggle>Dark mode</button>
:root {
  --bg: #fff;
  --fg: #111;
}
[data-theme='dark'] {
  --bg: #111;
  --fg: #eee;
}

How it works

  1. The mode is read from localStorage, or defaultMode ('system') when nothing is stored. It is a theme name or 'system'.
  2. The mode is resolved to a theme: 'system' becomes 'light' or 'dark' from prefers-color-scheme.
  3. The theme is written on <html> as data-theme (or a class), with color-scheme for native controls and an optional <meta name="theme-color">.
  4. A new choice is stored, applied without CSS transitions and reported to listeners and a themechange event.
  5. While in system mode, a change in the operating system updates the page. A choice made in another tab updates this one.

Pieces

JobHow
No flash on loadThe CDN script in <head>, or themeScript() inlined there
A dark mode buttondata-theme-toggle
Light, dark or systemdata-theme-set="light", radios, or select[data-theme-select]
From codecreateTheme(), then set(), toggle(), subscribe()
More themesthemes: ['light', 'dark', 'sepia']
Browser UI colorthemeColor
Theme a widget onlytarget and scope

Choose your next step