FluentCss documentation

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

Because the selector is a descendant combinator, the element that carries 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 keeps the choice in localStorage and applies it before the page paints.

// Apply the saved choice before the page paints
var saved = localStorage.getItem('fluentcss-theme');
if (saved === 'dark' || (!saved && matchMedia('(prefers-color-scheme: dark)').matches)) {
    document.documentElement.classList.add('theme-dark');
}

// Toggle it somewhere (for example a button)
function fcToggleTheme() {
    document.documentElement.classList.toggle('theme-dark');
}

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

Continue to the color palette.