Easy dark mode for Astro websites. Add themes in 2 lines of code! Zero dependencies, supports SSR, and works with any framework or UI.
npm install --save-dev astro-themesAdd the <Themes /> component in your app. Works best in a centralized layout component, so it's shared everywhere.
astro-themes gives you the ability to get and set the theme, with builtin browser standards. No polluting the global
scope or any other hacks! These methods will work without a framework, or from within your React/Svelte/Vue/etc
components.
Set the theme:
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'dark' })) // or pass `null` to clear the saved settingGet the current resolved theme and theme preference:
document.documentElement.attributes.getNamedItem('data-theme')?.value // 'light' | 'dark'
document.documentElement.attributes.getNamedItem('data-theme-preference')?.value // 'light' | 'dark' | ''Set a default theme (only applied if the browser doesn't specify a preference for dark mode):
<Themes defaultTheme="dark" />By default, Tailwind expects class="dark" on the html element rather than data-theme. To ensure that dark: classes work correctly, you can configure your dark mode selector as described here.
- Provides ability to get and set the theme from any framework, or none at all
- Set theme by dispatching a custom browser event:
document.dispatchEvent(new CustomEvent('set-theme', { detail: 'dark' })) - Get current theme:
document.documentElement.attributes.getNamedItem('data-theme')?.value
- Set theme by dispatching a custom browser event:
- Sets
data-themeattribute on thehtmlelement, so you can implement dark mode in CSS - Sets
color-schemeCSS attribute on thehtmlelement, so the browser renders built in elements appropriately - Reads user theme preference on page load
- From
localStorage, if they've set it in the past - From
prefers-color-scheme: dark, if supported - Falls back to the
defaultThemeoption, orlightif not specified
- From
- Synchronizes setting across tabs
- Responds to changes in OS preference (for example, the OS automatically switching to dark mode in the evening)
gh repo clone alex-grover/astro-themes
cd astro-themes
npm install
npm link
npm link astro-themes
npm run exampleIdeas, bug reports, or questions are welcomed! Please don't hesitate to open an issue.
This component was inspired by the excellent next-themes.
