Lesson 3 — Dark mode
How it works
Dark mode in Tailwind v4 is pure CSS — no JavaScript needed at this
stage. We override the token values inside a
@media (prefers-color-scheme: dark) block. Because every component
references tokens rather than raw palette values, they adapt
automatically — no dark-mode-specific component code needed.
Adding dark mode to application.css
Add the @media block after your @theme block:
|
|
Set your OS to dark mode and reload the browser — every component should switch colours automatically.
Updating AppLayout
Add bg-surface and text-text to body so the page background
and base text colour follow the active theme:
|
|
Also add a color-scheme meta tag to the <head> so the browser
renders native UI elements (scrollbars, form inputs) in the correct
mode:
|
|
What we don’t have yet
At this point dark mode is automatic — it follows the OS. There is
no way for the user to override it from within the app. In Lesson 5
we add a ThemeToggle Stimulus controller that lets users switch
manually, with their preference saved to localStorage.
The controller looks good but needs updating to handle the three-way interaction between system preference, manual override, and localStorage. Here’s the revised lesson: