Dark mode and themes
A theme is an ancestor class. Build theme-aware styles with the Dark root, or create your own with Theme(name).
The Dark root
Dark is a shortcut for
Theme("dark"). It prefixes every utility in the chain
with theme-dark:.
Dark
.Background(Color.Slate800)
.Color(Color.Slate100)
.Hover(h => h.Background(Color.Slate700));
// classes:
// theme-dark:bg-slate-800
// theme-dark:text-slate-100
// theme-dark:hover:bg-slate-700
How the selector is built
A themed utility is scoped by an ancestor that carries the theme class. The generated selector has two parts: the theme scope and the escaped utility class.
/* .theme-dark is the ancestor, the theme class is escaped */
.theme-dark .theme-dark\:bg-slate-800 { background-color: oklch(0.279 0.041 260.031) }
.theme-dark .theme-dark\:text-slate-100 { color: oklch(0.968 0.007 247.896) }
Theme class goes on an ancestor
theme-dark must be an ancestor of the styled element.
Put it on <html> or a wrapper element, not on the
same element that also uses the @Dark utilities.
Toggling the theme
Toggling is plain DOM work: add or remove the theme class. This documentation site persists the
choice in a cookie and reads it on the server, so the theme class is part of the rendered
<html> element and the page never flashes the
light theme first. localStorage is kept as a fallback
for first visits.
// Read the saved choice. The server reads the same cookie to render the
// theme class on <html>, so this only handles the first visit.
var theme = readCookie('fluentcss-theme') || localStorage.getItem('fluentcss-theme');
if (theme !== 'dark' && theme !== 'light') {
theme = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
document.documentElement.classList.toggle('theme-dark', theme === 'dark');
// Toggle it somewhere (for example a button) and persist the choice.
function fcToggleTheme() {
var dark = document.documentElement.classList.toggle('theme-dark');
document.cookie = 'fluentcss-theme=' + (dark ? 'dark' : 'light') +
';path=/;max-age=31536000;samesite=lax';
}
This card follows the theme.
Use the toggle in the header to switch between light and dark.
<div class="@Css.P(6).RoundedLg().Border().BorderColor(Color.Slate200)
@Css.Background(Color.White)
@Dark.Background(Color.Slate800).BorderColor(Color.Slate700)">
This card follows the theme.
</div>
Custom themes
Anything you can pass to Theme becomes a theme. The same
mechanism can drive high-contrast modes, seasonal skins or brand variants.
Theme("halloween")
.Background(Color.Orange500)
.Color(Color.Black);
// classes: theme-halloween:bg-orange-500 theme-halloween:text-black
// add the class "theme-halloween" to an ancestor to activate it