4 · Dark mode

Lesson 4 of 8 — add a dark theme with the `dark:` modifier and a toggle that remembers the choice.

1 min readv1

You will learn: the dark: modifier · class vs media strategy · building a toggle.

One modifier#

dark: applies a rule only when dark mode is on:

HTML
Toggle this site's theme (top right) — this card follows it.
<div nib="p=20px; bdrd=12px; bgc=#fff; cl=#0f172a; bd=1px solid #e2e8f0;
            dark:bgc=#0f172a; dark:cl=#e2e8f0; dark:bd=1px solid #1e293b">
  Toggle this site's theme (top right) — this card follows it.
</div>

Two strategies#

Pick one in nibcss.config.ts with darkMode:

darkMode

CSS

Controlled by

"class" (default)

.dark .nib-x { … }

A dark class on <html> — you add a toggle

"media"

@media (prefers-color-scheme: dark)

The operating system — no toggle

false

nothing

Every dark: rule is dropped

A toggle (class strategy)#

The runtime ships toggleDarkMode(): it flips html.dark, remembers the choice in localStorage, and follows the OS until the user makes one.

HTML
<button nib="p=8px 12px; bdrd=8px; bd=1px solid #cbd5e1; cur=pointer" onclick="Nib.toggleDarkMode()">
  Toggle theme
</button>

Design tip: tokens beat repeated colours#

Writing dark:bgc=#0f172a on every surface gets repetitive. In the next lesson you move colours into tokens, and in lesson 6 into recipes, so a surface is simply nib="card" in both themes.

Next steps#