Core concepts
Dark mode
The `dark:` variant styles an element in dark mode. It follows the system setting, or a `dark` class you control.
The dark: variant
Write the light style, then what changes in dark mode:
div(classes: 'p:6 br:xl bg:white c:gray-900 dark:bg:gray-900 dark:c:gray-100', [
.text('Readable in both modes'),
])
Following the system
By default (dark_mode: media),
dark: compiles to a
prefers-color-scheme
media query: the page follows the operating system, with no code.
dark
:
bg
:
gray-900
@media (prefers-color-scheme: dark) {
.dark\:bg\:gray-900 {
background-color: #111827;
}
}
A manual toggle
With dark_mode: class,
dark: applies under an element with the
dark class. Put it on
<html> and switch it from your code:
dark_mode: class
.dark .dark\:bg\:gray-900 {
background-color: #111827;
}
Writing the toggle
A client component flips the class and remembers the choice. This site uses the same approach, with a small script in
<head> that applies the saved choice before the first paint, so the page never flashes the wrong theme.
@client
class ThemeToggle extends StatelessComponent {
const ThemeToggle({super.key});
@override
Component build(BuildContext context) {
return button(
attributes: {'type': 'button', 'aria-label': 'Toggle dark mode'},
onClick: () {
final root = web.document.documentElement!;
final dark = root.classList.toggle('dark');
web.window.localStorage.setItem('theme', dark ? 'dark' : 'light');
},
[.text('Theme')],
);
}
}
Components
JX Components ship dark:
variants for their surfaces, text and tones. They follow whichever dark_mode
your project uses, since the CLI compiles their classes with your configuration.