Theming
Every colour, mode, contrast level, motion scheme and density is driven by tokens. Pick one of six built-in themes, generate your own from a seed colour, and switch any of the five dimensions at runtime or per subtree.
Try it
This live demo drives a ThemeScope around the preview card, so the controls re-theme the card without touching the rest of the page.
The five dimensions
- Theme — six built-ins: baseline (the default, seed
#6750A4), ocean (#0061A4), forest (#386A20), sunset (#A04100), rose (#9C4146) and slate (#545F71, the onlyneutralvariant; the rest aretonal-spot). Scheme variants aretonal-spot,neutral,vibrantandexpressive. - Mode —
light,darkorsystem.systemfollowsprefers-color-schemeand resolves toresolvedModeonuseTheme(). - Contrast —
standard,mediumorhigh. - Motion —
expressive(the default) orstandard. See the Motion guide. - Density —
0(the default) to-3, on the web only. See Density.
ThemeProvider
Each dimension is controlled (theme/mode/contrast/motion with the matching onChange) or uncontrolled (the default* props). The selection is remembered via storage (cookie by default, or local-storage/none) under storageKey (default windmorph-theme), read with useSyncExternalStore so there is no hydration mismatch, and written only once the selection changes, so a visitor who picks nothing gets no cookie. Only the person's own choices are stored: a dimension the app controls keeps the value stored for it, so an app can force a mode for a while and the visitor's own comes back when it stops. The browser's saved selection is applied right after hydration; with a streaming server, read the cookie there and pass every value as a default* prop (see No theme flash), since a theme change after hydration makes React render the Suspense boundaries still streaming on the client. applyToDocument (default true) writes the data-* attributes to <html>.
import { ThemeProvider } from '@windmorph/react';
<ThemeProvider
defaultTheme="baseline" // one of the six built-ins, or a createTheme() name
defaultMode="system" // light | dark | system
defaultContrast="standard" // standard | medium | high
defaultMotion="expressive" // expressive | standard
storage="cookie" // cookie (default) | local-storage | none
storageKey="windmorph-theme"
>
{children}
</ThemeProvider>;Reading & scoping the theme
useTheme() returns the current theme, mode, contrast, motion, resolvedMode and themes, plus setTheme/setMode/setContrast/setMotion. It throws outside a provider. useThemeScope() returns the effective state at a point in the tree.
import { useTheme } from '@windmorph/react';
function ThemeMenu() {
const { theme, themes, setTheme, mode, setMode, resolvedMode } = useTheme();
// theme / mode / contrast / motion plus resolvedMode (system -> light|dark)
// and setters. Throws if used outside a ThemeProvider.
}ThemeScope re-themes a subtree. Any of its five props (theme, mode, contrast, motion and density) can be set; the rest inherit, and scopes nest. It renders a div; inside content that takes only phrasing content, such as a button, a p or a label, as="span" renders a span that does everything the same.
The dark: variant follows the nearest scope with a mode, its system read from the device: inside a light scope on a dark page it doesn't apply, and inside a dark scope within that light one it does again. That holds for scopes nested up to three deep, which covers a page, a scope and an overlay or card inside it.
import { ThemeScope } from '@windmorph/react';
// Theme a subtree. Unset dimensions inherit from the nearest provider or scope; scopes nest.
<ThemeScope theme="forest" mode="dark">
<PricingCard />
</ThemeScope>;Density
On the web, M3 lets components be denser: density goes from 0 (the default) to -3, and each step takes 4px off a component's height by trimming the padding above and below its content. Text fields, selects and autocompletes go from 56px to 44px, menus and their options from 44px to 32px items, and the typed fields of the date and time pickers follow. The date picker's calendar and the time picker's dial keep their size, since their 48px targets are part of their accessibility.
The controls follow too, after Material Components Web's density: checkboxes and radio buttons shrink their state layer from 40px to 28px (a radio group keeps its rows 48px apart), a switch its state layer from 40px to 32px, chips go from 32px to 24px (a chip set keeps its rows 48px apart), icon buttons lose 4px of height and width at every size (a small one 40px to 28px), so button groups of them follow, tabs go from 48px to 36px (64px to 52px with icons above), and list items lose 4px a step (one line 56px to 44px), section subheaders too.
Icon buttons keep their size where the part around them keeps its own: in a text field's icon slots, on the pickers, in top app bars and search app bars, in docked and floating toolbars (their button groups too), in search bars and their views, in a navigation rail's header, and in full-screen dialog and side sheet headers, beside a bottom sheet's drag handle too. An icon button's own density still wins. Buttons have no density: for a denser layout, use a smaller size.
Set it app-wide with ThemeProvider (density / defaultDensity / onDensityChange, and setDensity on useTheme(); it's stored with the theme), for a section with ThemeScope density, or on one component with its density prop, which wins. Each writes a data-density attribute that sets --md-sys-density for everything inside, so density is plain CSS: it works in server-rendered and static pages, and menus and other overlays take the density of where they open.
import { ThemeProvider, ThemeScope, TextField, useTheme } from '@windmorph/react';
// App-wide: the reader's choice, remembered with the rest of the theme.
<ThemeProvider defaultDensity={0}>{children}</ThemeProvider>;
function DensitySetting() {
const { density, setDensity } = useTheme(); // 0 | -1 | -2 | -3
// Offer it as a setting, with controls of 48px or more (see below).
}
// A section, e.g. a data-heavy admin table's filters:
<ThemeScope density={-2}>
<Filters />
</ThemeScope>;
// One component, overriding the theme:
<TextField label="Search" density={0} />;- Make it a choice, not a default. M3: "Don't apply density to text fields by default. This lowers their targets below the recommended 48x48 CSS pixels. Instead, give people a way to choose a higher density, like selecting a denser layout or changing the theme." This site's display settings have one.
- Keep the way back easy. The control that changes density keeps 48px targets at every level (M3: "keep all the targets to change it at a minimum of 48x48 CSS pixels"); a button group of small buttons, as in the display settings, does.
- Targets. A dense field still answers a press within 48px of its centre, and its icon buttons keep 48px targets. Dense checkboxes, radio buttons, switches, chips and icon buttons keep 48 × 48px targets that reach past their containers (M3: chips "must also have a minimum 48dp target size, regardless of placement or density"), and the chip sets, radio groups and autocomplete fields that stack them keep their rows 48px apart, so two targets never overlap. The one narrower target is the remove button beside a chip's toggle or action: 41px wide, so it never covers the chip's label. Dense menu items (40, 36 and 32px), tabs and list items are adjacent rows, so their targets can't reach 48px without overlapping the next one; they stay above WCAG 2.5.8's 24px minimum, and density is the reader's own choice.
Custom themes
createTheme() generates a theme from a seed colour with the M3 2025 colour spec. Pass the result in ThemeProvider’s themes prop.
import { createTheme, ThemeProvider } from '@windmorph/react';
const acme = createTheme({ name: 'acme', seed: '#0B57D0' });
// variant defaults to 'tonal-spot'; contrast defaults to all three levels.
<ThemeProvider themes={['baseline', acme]} defaultTheme="acme">
{children}
</ThemeProvider>;For static sites, the CLI writes the same CSS to a file. The only subcommand is theme.
# Generate a static CSS theme (light, dark and system for each contrast level).
npx @windmorph/react theme --seed "#0B57D0" --name acme --out acme-theme.css
# Options: --variant tonal-spot|neutral|vibrant|expressive (default tonal-spot),
# --palette <name>=<source> (repeatable, see Mixing palettes),
# --custom success|warning=<hex>, --no-harmonize (see Success and warning),
# --contrast standard,medium,high (default all), --out <file> (else stdout).Mixing palettes
An M3 scheme is built from six tonal palettes, the core colours of Material Theme Builder: primary, secondary, tertiary, error, neutral and neutralVariant. The palettes option takes any of them from another variant of the same seed, or from a hex colour. Every role still takes its tone from the M3 spec for the theme's own variant, so text keeps its contrast.
A common use is vivid accents on calm surfaces: vibrant tints the surfaces too, which can be strong in dark mode, so take the neutral palettes from tonal-spot. A hex neutral keeps its own chroma, so pick a greyish one; a variant source is the easy way to calm surfaces.
A brand's second colour goes in a palette too. This site's own theme is built that way: the Windmorph logo's blue is the seed, its teal is the tertiary palette, and the neutrals come from tonal-spot.
vibrantJoin the community
Light mode: surface and card colours.
Join the community
Dark mode: surface and card colours.
vibrant + tonal-spot neutralsJoin the community
Light mode: surface and card colours.
Join the community
Dark mode: surface and card colours.
import { createTheme } from '@windmorph/react';
// Vivid accents on calm, nearly neutral surfaces.
const blue = createTheme({
name: 'blue',
seed: '#1877F2',
variant: 'vibrant',
palettes: { neutral: 'tonal-spot', neutralVariant: 'tonal-spot' },
});
// A brand's two colours: this site's theme takes the logo's blue as the seed and its
// teal as the tertiary palette, on the same calm surfaces.
const windmorph = createTheme({
name: 'windmorph',
seed: '#1F5AAB',
variant: 'vibrant',
palettes: { tertiary: '#2CDECE', neutral: 'tonal-spot', neutralVariant: 'tonal-spot' },
});
// The CLI takes the same option:
// npx @windmorph/react theme --name blue --seed "#1877F2" --variant vibrant \
// --palette neutral=tonal-spot --palette neutral-variant=tonal-spotimport { Button, Card, createTheme, ThemeScope } from '@windmorph/react';
/** The same blue seed twice: `vibrant` alone, and `vibrant` with tonal-spot neutrals. */
const vivid = createTheme({ name: 'demo-vivid', seed: '#1877F2', variant: 'vibrant' });
const calm = createTheme({
name: 'demo-calm',
seed: '#1877F2',
variant: 'vibrant',
palettes: { neutral: 'tonal-spot', neutralVariant: 'tonal-spot' },
});
const COLUMNS = [
{ theme: vivid, label: 'vibrant' },
{ theme: calm, label: 'vibrant + tonal-spot neutrals' },
] as const;
/**
* Vivid accents on calm surfaces: the second theme keeps the vibrant buttons and
* containers, and takes its surfaces from the tonal-spot neutrals. Rendered on the server.
*/
export function PalettesDemo() {
return (
<div className="grid w-full gap-4 medium:grid-cols-2">
{[vivid, calm].map((theme) => (
<style key={theme.name} href={`docs-${theme.name}`} precedence="windmorph">
{theme.css}
</style>
))}
{COLUMNS.map(({ theme, label }) => (
<div key={theme.name} className="flex min-w-0 flex-col gap-2">
<code className="truncate text-body-small text-on-surface-variant">{label}</code>
{(['light', 'dark'] as const).map((mode) => (
<ThemeScope
key={mode}
theme={theme.name}
mode={mode}
className="flex flex-col gap-3 rounded-corner-large bg-surface p-4"
>
<Card variant="filled" className="flex flex-col gap-3 p-4">
<p className="text-title-medium text-on-surface">Join the community</p>
<p className="text-body-medium text-on-surface-variant">
{mode === 'light' ? 'Light mode' : 'Dark mode'}: surface and card colours.
</p>
<div className="flex flex-wrap gap-2">
<Button variant="filled" size="sm">
Sign up
</Button>
<Button variant="tonal" size="sm">
Learn more
</Button>
</div>
</Card>
</ThemeScope>
))}
</div>
))}
</div>
);
}Success and warning
M3 has no key colour for success or warning, so every theme adds them the way Material Theme Builder makes custom colours: a green and an amber, turned slightly toward the seed so they belong to the theme, each with success, on-success, success-container and on-success-container roles (and the same for warning). Their tones follow M3's error roles, so they have the same contrast in every mode and at every contrast level.
customColors sets your own, and harmonize: false keeps their exact hues.
import { createTheme } from '@windmorph/react';
// Every theme has success and warning roles: a green and an amber, harmonised to the seed.
<span className="bg-success-container text-on-success-container">Paid</span>;
<span className="bg-warning-container text-on-warning-container">Payment pending</span>;
// A brand's own status colours, at their exact hues.
const shop = createTheme({
name: 'shop',
seed: '#0B57D0',
customColors: { success: '#0B8043', warning: '#E37400' },
harmonize: false,
});
// The CLI takes the same options:
// npx @windmorph/react theme --name shop --seed "#0B57D0" \
// --custom success=#0B8043 --custom warning=#E37400 --no-harmonizeOverriding tokens
The five attributes are data-theme, data-mode, data-contrast, data-motion and data-density. Override any token with a plain rule after the library stylesheet: :root for the page and the menus, dialogs and tooltips opened from it, or [data-theme="ocean"] for one theme. The themes set --md-sys-color-* on zero-specificity :where() selectors, so your rule always wins, in every mode and contrast level. A literal colour is the same in light and dark mode, so check its contrast in both, or generate a theme instead.
A ThemeScope, and an overlay opened inside one, carries only the attributes that differ from the page, so a :root value reaches everything it doesn't change. One that changes the theme, mode or contrast, or has a className or style variables of its own (which may set a colour role, so the shadows follow it), sets that theme's colours and elevation again on its own element, and one that changes the motion scheme its springs: for a value that holds there too, write :root, [data-theme] (colours and elevation) or :root, [data-motion] (motion). Put motion values inside @media (prefers-reduced-motion: no-preference), or they replace the 0ms spatial springs reduced motion sets.
/* The page and its menus, dialogs and tooltips, after the library stylesheet. */
:root {
--md-sys-shape-corner-full: 12px;
--md-ref-typeface-brand: 'Inter';
}
/* Colours and elevation in every theme, ThemeScopes that re-theme a subtree too. */
:root,
[data-theme] {
--md-sys-color-tertiary: #7d5260;
}
/* One theme, in every mode and contrast level. */
[data-theme='ocean'] {
--md-sys-color-primary: #0050c8;
}
/* Motion in every scheme and scope, leaving reduced motion's 0ms in place. */
@media (prefers-reduced-motion: no-preference) {
:root,
[data-motion] {
--md-sys-motion-spring-spatial-fast-duration: 300ms;
}
}No theme flash
With a server, read the cookie: getThemeFromCookies() from @windmorph/react/next and render <html {...themeAttributes(theme)}> and pass every value to ThemeProvider as its default* prop — see the Next.js guide. For a static or exported site, render ThemeScript in <head> with suppressHydrationWarning on <html>. ThemeScript and DEFAULT_THEME_STATE ({ theme: "baseline", mode: "system", contrast: "standard", motion: "expressive", density: 0 }) come from @windmorph/react, not /next.
// Static / exported sites: ThemeScript applies the stored theme before first paint.
import { DEFAULT_THEME_STATE, ThemeScript } from '@windmorph/react';
<html lang="en" suppressHydrationWarning>
<head>
<ThemeScript defaults={DEFAULT_THEME_STATE} />
</head>
{/* ThemeScript is exported from @windmorph/react, not @windmorph/react/next. */}
</html>;API reference
ThemeProvider 19 props
themestypereadonly ("baseline" | "ocean" | "forest" | "sunset" | "rose" | "slate" | ThemeDefinition)[]Themes available to
setTheme: built-in names and/orcreateTheme()results. Defaults to all six built-in themes.Controlled colour theme.
Initial colour theme when uncontrolled.
Controlled colour mode.
Initial colour mode when uncontrolled.
Controlled contrast level.
Initial contrast level when uncontrolled.
Controlled motion scheme.
Initial motion scheme when uncontrolled.
Controlled web density,
0to-3: each step takes 4px off the height of fields, menus and other dense-capable components. M3 asks for density to be the reader's choice, not a default, so offer it as a setting; keep the control that changes it at 48px or more.Initial web density when uncontrolled.
Where the selection is remembered. Use
"cookie"(default) withgetThemeFromCookiesorThemeScriptfor flash-free server rendering. Nothing is written until the selection changes from the one the page loaded with, so a visitor who never picks a setting gets no cookie. Only the person's own choices are stored: a dimension the app controls (mode="dark"for a while) keeps the value stored for it, so their choice is back when the app lets go.The browser's saved selection is applied right after hydration. When it differs from what the server rendered, React renders any Suspense boundary still streaming (a Next.js
loading.tsx) on the client, dropping its server HTML. A streaming server should read the cookie withgetThemeFromCookiesand pass every value as adefault*prop; a development warning names the values when it doesn't.Cookie or localStorage key.
Whether the theme attributes are written to
<html>. Set tofalsewhen you render them yourself or theme a subtree withThemeScopeinstead.
Events
Called with the new colour theme when it changes.
Called with the new colour mode when it changes.
Called with the new contrast level when it changes.
Called with the new motion scheme when it changes.
Called with the new density when it changes.
ThemeScope 9 props
Colour theme for this subtree. Inherited when omitted.
Colour mode for this subtree. Inherited when omitted.
Contrast level for this subtree. Inherited when omitted.
Motion scheme for this subtree. Inherited when omitted.
Web density for this subtree,
0to-3(e.g. a dense data table's filters). Inherited when omitted.The element: a
div, or aspanfor a scope inside content that takes only phrasing content, where adivisn't allowed (a<button>, a<p>, a<label>). The ref receives it.The scope's element: a
div, or thespanofas="span".
Also accepts the root element's HTML attributes (id, data-*, event handlers).
ThemeScript 4 props
Values used when nothing is stored. Must match the
ThemeProviderdefaults.Must match
ThemeProvider'sstorage.Must match
ThemeProvider'sstorageKey.CSP nonce for the inline script.
useTheme
useTheme(): ThemeContextValueReads and changes the app theme set by ThemeProvider.
Returns ThemeContextValue
modewith"system"resolved fromprefers-color-scheme.Names of the themes available to
setTheme.Switches the colour theme; a name not in
themesis ignored (with a warning in development).Switches the colour mode:
light,darkorsystem.Switches the contrast level:
standard,mediumorhigh.Switches the motion scheme:
expressiveorstandard.Switches the web density,
0to-3.The colour theme's name: a built-in (
baseline,ocean…) or one made withcreateTheme.light,darkorsystem(followsprefers-color-scheme).standard,mediumorhigh.expressive(springs that overshoot) orstandard(no visible overshoot).Web density,
0(default) to-3(densest); seeDensity.
useThemeScope
useThemeScope(): ThemeStateThe theme state in effect at this point in the tree, including any ThemeScope.
Returns ThemeState
The colour theme's name: a built-in (
baseline,ocean…) or one made withcreateTheme.light,darkorsystem(followsprefers-color-scheme).standard,mediumorhigh.expressive(springs that overshoot) orstandard(no visible overshoot).Web density,
0(default) to-3(densest); seeDensity.