- Docs
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
- The mode is read from
localStorage, ordefaultMode('system') when nothing is stored. It is a theme name or'system'. - The mode is resolved to a theme:
'system'becomes'light'or'dark'fromprefers-color-scheme. - The theme is written on
<html>asdata-theme(or a class), withcolor-schemefor native controls and an optional<meta name="theme-color">. - A new choice is stored, applied without CSS transitions and reported to listeners and a
themechangeevent. - While in system mode, a change in the operating system updates the page. A choice made in another tab updates this one.
Pieces
| Job | How |
|---|---|
| No flash on load | The CDN script in <head>, or themeScript() inlined there |
| A dark mode button | data-theme-toggle |
| Light, dark or system | data-theme-set="light", radios, or select[data-theme-select] |
| From code | createTheme(), then set(), toggle(), subscribe() |
| More themes | themes: ['light', 'dark', 'sepia'] |
| Browser UI color | themeColor |
| Theme a widget only | target and scope |
Choose your next step
Package managers, the CDN and the first toggle.
ExamplesLive previews with the complete, copyable source of each one.
API referenceSignatures and behavior of createTheme, themeScript, the controller and window.Theme.
Options, controls and script attributes.
Styling and renderingCSS, custom themes, server rendering, widgets and transitions.
Accessibility and contrastFocus, reduced motion and what your page provides.
Framework integrationsReact, Vue, Svelte, Astro and Next.js.