Theming

How matix/ui theming works, creating custom themes with stylex.createTheme(), manual dark mode toggle, brand token customization, and high-contrast mode.

matix/ui themes are browser-native. Light mode, dark mode, and high-contrast mode are all handled via CSS media queries baked into the token definitions — no JavaScript, no React context, no hydration mismatch. The browser resolves the correct theme before first paint.


Supported Styling Model

matix/ui deliberately uses one visual customization system. Choose documented component props and variants, apply a matix or custom StyleX theme, or use the typed sx prop for a per-instance override.

Styled component roots do not expose className as a general styling escape hatch. Generated classes, internal selectors, undocumented CSS variables, and DOM structure are not stable override targets. Plain CSS, CSS Modules, and Tailwind are therefore not supported component-styling paths. Unstyled composition primitives may still forward native classes when matix does not own their appearance. A class that reaches a styled part anyway, from a render element or a {...stylex.props()} spread, is added to the part's own classes. It never replaces them, and the matix value wins a conflict.

Default components use matix's precompiled styles. Configure the StyleX compiler in your application only when authoring custom themes or sx styles. For surrounding application layout, use a wrapper or an sx layout rule on the component.


How It Works

All color tokens are defined with stylex.defineVars() in @matix/tokens. Each token has three values:

  • default — used in light mode
  • @media (prefers-color-scheme: dark) — used when the OS is in dark mode
  • @media (forced-colors: active) — used in Windows High Contrast Mode, mapped to system colors
// @matix/tokens — colors.stylex.ts (abbreviated)
import * as stylex from '@stylexjs/stylex';

const DARK = '@media (prefers-color-scheme: dark)';
const HC   = '@media (forced-colors: active)';

export const colors = stylex.defineVars({
  bgBase:       { default: '#ffffff', [DARK]: '#09090b', [HC]: 'Canvas'     },
  fgBase:       { default: '#09090b', [DARK]: '#fafafa', [HC]: 'CanvasText' },
  border:       { default: '#e4e4e7', [DARK]: '#27272a', [HC]: 'CanvasText' },
  borderStrong: { default: '#a1a1aa', [DARK]: '#52525b', [HC]: 'CanvasText' },
  // ... all color tokens follow this shape
});

StyleX compiles these into nested @media rules inside the :root declaration. No JavaScript runs. No context reads happen. The browser does all the work.

Spacing, radii, typography, shadows, surface, and the chart palette are defineVars CSS variables too, so a theme can override them. Only motion and z-index use stylex.defineConsts(). The compiler inlines them, and you cannot theme them.


Seeds and Derived Tokens

Each color family grows from one seed. The seeds live in @matix/tokens/seeds.stylex — one each for primary, destructive, success, warning and info. Every other token in a family is a color-mix() over its seed variable, so overriding the seed recolors the family and the browser does the arithmetic at paint time.

import * as stylex from '@stylexjs/stylex';
import { seeds } from '@matix/tokens/seeds.stylex';

// One value. Hover, active, the tinted soft background and the text
// that sits on the fill all follow.
export const blueTheme = stylex.createTheme(seeds, {
  primary: '#2563eb',
});

Put a seeds theme on html

A seeds theme works only on <html>. The derived tokens are declared on :root, and CSS resolves each color-mix() once there. A seeds theme on <body> or on a subtree changes the seed variable. It does not change the derived colors. The solid Badge, for example, keeps its default color.

// app/layout.tsx
import * as stylex from '@stylexjs/stylex';
import { blueTheme } from '../tokens/blue-theme.stylex';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" {...stylex.props(blueTheme)}>
      <body>{children}</body>
    </html>
  );
}

To scope a theme to a subtree, override colors (and surface, and so on), not seeds. The next section shows how. The bundled themes contain seeds, so apply them to <html> too.

Two decisions can't be expressed as a plain mix, so the tokens read the seed's own OKLab lightness with relative color syntax:

  • Hover direction. A fill gains contrast against the page by darkening in light appearance and lightening in dark — except near the extremes, where it can only move one way. A near-black primary lightens on hover in both appearances.
  • On-color. onPrimary and onDestructive flip between near-white and near-black at the lightness where black text overtakes white, so a seed override can't leave pale text on a pale fill.
// colors.stylex.ts — how a derived token is written
primaryHover: {
  default: {
    // Literal fallback first, for browsers without relative color syntax.
    default: '#2f2f32',
    [RCS]: `color-mix(in oklab, ${seeds.primary} 88%,
      oklch(from ${seeds.primary} clamp(0, (0.35 - l) * infinity, 1) 0 h))`,
  },
  // ... [DARK] branch, then [HC]
},

Mixes interpolate in oklab, never oklch. OKLCH interpolates the hue channel, so an anchor with any chroma at all pulls the seed's hue toward its own — a lime seed mixed into zinc-950 lands on teal. OKLab scales the a/b pair and preserves hue.

Pin a derived token whenever the design wants a specific value. A pin always wins over the derivation.

The primary scale

Themes that expose a primary control also emit a Tailwind-shaped ramp from the same seed, as --mtx-primary-50 through --mtx-primary-950. Step 500 is the seed itself, and 50 is always the lightest step whatever the seed's lightness. No component reads these — they exist so app code can reach the user's primary at a specific tint.

.callout {
  background: var(--mtx-primary-50);
  border-left: 3px solid var(--mtx-primary-500);
  color: var(--mtx-primary-900);
}

Derived tokens need color-mix() and relative color syntax: Chrome 119, Safari 16.4, Firefox 128 and up. Tokens using relative color syntax carry an @supports fallback, so older browsers get the stock ramp rather than a broken one.


Creating a Custom Theme

Use stylex.createTheme() to override any subset of the color tokens. Unspecified tokens fall back to their defaults.

// brand-theme.stylex.ts
// NOTE: createTheme() calls must be in .stylex.ts files.
// The StyleX compiler requires static analysis of these files.
import * as stylex from '@stylexjs/stylex';
import { colors } from '@matix/tokens/colors.stylex';

export const brandTheme = stylex.createTheme(colors, {
  primary:        '#6366f1',  // Indigo 500
  onPrimary:      '#ffffff',
  primaryHover:   '#4f46e5',  // Indigo 600
  primaryActive:  '#4338ca',  // Indigo 700
  bgSubtle:      '#f5f3ff',  // Indigo 50
  bgMuted:       '#ede9fe',  // Indigo 100
  borderFocus:   '#6366f1',
  // All other tokens keep their defaults
});

Apply the theme by spreading it onto any wrapping element:

// app/layout.tsx (Next.js App Router)
import '@matix/components/globals.css';
import * as stylex from '@stylexjs/stylex';
import { brandTheme } from '../tokens/brand-theme.stylex';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body {...stylex.props(brandTheme)}>
        {children}
      </body>
    </html>
  );
}

The theme applies to all matix/ui components inside the wrapped element. You can nest themes to scope them to specific subtrees.

// Scoping a theme to a specific section of the UI
import * as stylex from '@stylexjs/stylex';
import { brandTheme } from './brand-theme.stylex';

export function MarketingSection({ children }: { children: React.ReactNode }) {
  return (
    <section {...stylex.props(brandTheme)}>
      {children}
    </section>
  );
}

Overlays do not follow a subtree theme. Dialog, Popover, Menu, Select, Tooltip, Drawer, and Toast render in a portal in <body>, outside the themed subtree. Put an app-wide theme on <html>. A colors theme also works on <body>.

For a subtree theme, pass container to the Portal of a Dialog, Popover, Menu, Tooltip, or Drawer. Give it a ref to an element inside the themed subtree. Select and Toast have no container, so they use the page theme.


Manual Dark Mode Toggle

By default, the tokens follow the OS prefers-color-scheme setting. For a manual toggle, import the appearance stylesheet once, next to the component styles:

import '@matix/components/globals.css';
import '@matix/tokens/appearance.css';

Then put one class on <html>. dark forces dark and light forces light. With neither class, the tokens follow the OS. The attribute data-appearance="dark" or "light" works the same way.

Every token with a dark branch follows the class. Dialogs, popovers, menus, toasts, and tooltips render in a portal inside <body>, so they follow the class on <html> too. A script compiles the stylesheet from the token sources, so its values cannot drift from the tokens. Forced-colors mode still wins over the class.

The class also works on a subtree. The preview below puts light on one wrapper and dark on the other:

Forced light

class="light"

Forced dark

class="dark"

Tokens with a dark branch

GroupDark branchSame in light and dark
seedsAll five—
colorsAll tokens. destructive, success, warning, and info read their seed, so they follow it.—
surfacebg, bgSubtle, borderColorblur, borderWidth, shadow, innerGlow
shadowsAll seven, including the ring offset colour—
chartsAll eight series—
spacing, radii, typography—All tokens

No flash in Next.js

The class must be on <html> before first paint. next-themes does this: it adds an inline script that reads the stored choice, or the OS setting, and sets the class before the page renders. You need no client wrapper around the app.

// app/layout.tsx
import '@matix/components/globals.css';
import '@matix/tokens/appearance.css';
import { ThemeProvider } from 'next-themes';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    // The server HTML has no class. The script adds it before hydration.
    <html lang="en" suppressHydrationWarning>
      <body>
        <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}
// components/appearance-toggle.tsx
'use client';

import { useTheme } from 'next-themes';
import { Button } from '@matix/components/button';

export function AppearanceToggle() {
  const { resolvedTheme, setTheme } = useTheme();
  return (
    <Button variant="ghost" onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}>
      Toggle appearance
    </Button>
  );
}

Without next-themes, write the same script yourself. Keep it inline in <head>, so it runs before first paint:

// app/layout.tsx
const appearanceScript = `try {
  var a = localStorage.getItem('appearance');
  if (a === 'dark' || a === 'light') document.documentElement.classList.add(a);
} catch (e) {}`;

<html lang="en" suppressHydrationWarning>
  <head>
    <script dangerouslySetInnerHTML={{ __html: appearanceScript }} />
  </head>
  ...
</html>

// The toggle
function setAppearance(next: 'light' | 'dark') {
  document.documentElement.classList.remove('light', 'dark');
  document.documentElement.classList.add(next);
  localStorage.setItem('appearance', next);
}

Themes and a manual toggle

The token half of the bundled themes (Swiss, Modern, Liquid Glass, Skeuomorphic, Claymorphic) follows the class. Their --mtx-* hook stylesheets follow it too.

A [DARK] branch in your own createTheme() follows the OS, not the class. For a manual toggle, keep the appearance out of the theme. Point the theme at your own CSS variables, and set those variables for each appearance in plain CSS:

// brand-theme.stylex.ts
import * as stylex from '@stylexjs/stylex';
import { seeds } from '@matix/tokens/seeds.stylex';

export const brandSeeds = stylex.createTheme(seeds, {
  primary: 'var(--brand-primary)',
});
/* brand.css */
:root,
.light {
  --brand-primary: #4f46e5;
}
.dark {
  --brand-primary: #818cf8;
}
@media (prefers-color-scheme: dark) {
  :root:not(.light) {
    --brand-primary: #818cf8;
  }
}

Brand Token Customization

The token shape in @matix/tokens is intentionally minimal. Every token that varies between light and dark mode is a defineVars CSS variable. All you need to do to apply a brand color is override primary, onPrimary, primaryHover, and primaryActive.

// Example: Violet brand
export const violetTheme = stylex.createTheme(colors, {
  primary:        '#7c3aed',  // Violet 600
  onPrimary:      '#ffffff',
  primaryHover:   '#6d28d9',  // Violet 700
  primaryActive:  '#5b21b6',  // Violet 800
  bgSubtle:      '#f5f3ff',  // Violet 50
  bgMuted:       '#ede9fe',  // Violet 100
  borderFocus:   '#7c3aed',
});

// Example: Rose brand
export const roseTheme = stylex.createTheme(colors, {
  primary:        '#e11d48',  // Rose 600
  onPrimary:      '#ffffff',
  primaryHover:   '#be123c',  // Rose 700
  primaryActive:  '#9f1239',  // Rose 800
  bgSubtle:      '#fff1f2',  // Rose 50
  bgMuted:       '#ffe4e6',  // Rose 100
  borderFocus:   '#e11d48',
});

Because these are CSS variables scoped to a DOM element, you can even apply different themes to different parts of the same page:

// Two themed sections on the same page
<div {...stylex.props(violetTheme)}>
  <Button variant="solid">Primary action</Button>   {/* violet */}
</div>

<div {...stylex.props(roseTheme)}>
  <Button variant="solid">Danger action</Button>    {/* rose */}
</div>

High-Contrast Mode

matix/ui's color tokens handle Windows High Contrast Mode automatically via the forced-colors: active media query. Every token maps to a semantic system color:

Token categorySystem color used
BackgroundsCanvas
Text / foregroundsCanvasText
Muted textCanvasText
Focus rings / primaryHighlight
Primary textHighlightText
BordersCanvasText
Semantic: destructive, success, warning, infoLinkText

When a user has forced colors enabled, the browser forces all CSS properties that use these system colors to the user's chosen high-contrast palette — no additional configuration required. matix/ui components will be readable and usable in all Windows High Contrast themes out of the box.

If you create a custom theme with createTheme(), include the forced-colors overrides:

// brand-theme.stylex.ts — with forced-colors support
import * as stylex from '@stylexjs/stylex';
import { colors } from '@matix/tokens/colors.stylex';

const HC = '@media (forced-colors: active)';

export const brandTheme = stylex.createTheme(colors, {
  primary:      { default: '#6366f1', [HC]: 'Highlight'     },
  onPrimary:    { default: '#ffffff', [HC]: 'HighlightText'  },
  primaryHover: { default: '#4f46e5', [HC]: 'Highlight'      },
  borderFocus: { default: '#6366f1', [HC]: 'Highlight'      },
  bgSubtle:    { default: '#f5f3ff', [HC]: 'Canvas'         },
  bgMuted:     { default: '#ede9fe', [HC]: 'Canvas'         },
});

Without the forced-colors overrides, high-contrast mode still works (the browser overrides any non-system color), but including explicit mappings ensures your theme is intentional rather than letting the browser guess.

More contrast without forced colors

The macOS and iOS “Increase contrast” setting sets prefers-contrast: more, but it does not turn on forced colors. These users see your normal theme. To give them more contrast, apply the high-contrast theme when the query matches. The theme is light-only and targets 7:1 for text.

import { useSyncExternalStore } from 'react';
import * as stylex from '@stylexjs/stylex';
import { highContrastTokens } from '@matix/tokens/themes/high-contrast';

const query = '(prefers-contrast: more) and (not (forced-colors: active))';

function subscribe(onChange: () => void) {
  const media = window.matchMedia(query);
  media.addEventListener('change', onChange);
  return () => media.removeEventListener('change', onChange);
}

export function ContrastRoot({ children }: { children: React.ReactNode }) {
  const more = useSyncExternalStore(
    subscribe,
    () => window.matchMedia(query).matches,
    () => false,
  );
  return <div {...stylex.props(...(more ? highContrastTokens : []))}>{children}</div>;
}

Important Constraints

  • createTheme() calls must be in .stylex.ts files. The StyleX compiler requires static analysis of theme definitions. If you put a createTheme() call in a regular .ts or .tsx file, the compiler will not process it correctly.
  • Import paths must be exact across package boundaries. StyleX's static analysis is strict. If you import tokens as @matix/tokens in one file and as a relative path in another, createTheme() may not correctly associate the theme with the token object.
  • Only defineVars tokens are themeable. Seeds, colors, surface, spacing, radii, typography, shadows, and charts are defineVars. Motion and z-index use defineConsts and are inlined at compile time. You cannot override them with createTheme().

Summary

Use caseSolution
Follow OS dark modeNothing — works automatically
Custom brand colorsstylex.createTheme(colors, { primary: '...' })
Manual dark mode toggle@matix/tokens/appearance.css, then class="dark" or class="light" on <html>
Scoped theme (one section)Apply theme to a wrapper element, not the root
High-contrast modeAutomatic via forced-colors token values