Custom Themes

How to build your own design language with theme-config.json — the cortex engine turns one config file into a complete token system.

FlexPixels ships one default look; cortex is the engine you use to replace it with your own. The main parts of a design language are set in config: colour seeds, spacing rhythm, radius and border character, elevation style (flat, neumorphic, brutalism or liquid-glass via elevation.style), glow and gradient borders, typography scenarios and motion timings. You change them in one file instead of overriding component CSS.

Quick start

  1. Create a theme-config.json in your project.
  2. Generate the CSS from it with a small build script that calls generateThemeCSS — see Build & Import.
  3. Load the generated CSS on your pages.

The whole theme is one CSS file of custom properties.


Configuration File

The theme config is validated against a strict Zod schema: unknown keys are errors. The schema requires seeds (primary, secondary, neutral): validateThemeConfig throws without it. loadConfigFromPath and mergeThemeConfig fill anything missing from the defaults, seeds included, so a file without seeds gets the default colours without an error. The theme-config.json reference lists every key, including the sections this page only touches on (sizes, layout, inset, scroll, dataviz, output).

Minimal Config

json
{
  "seeds": {
    "primary": "#4f46e5",
    "secondary": "#c026d3",
    "neutral": "#94a3b8"
  }
}

Three colours is all you need. The engine generates success, danger, warning and info at fixed hue anchors (145° / 25° / 85° / 250°), using the primary’s chroma, raised to at least 0.12 and capped to what sRGB holds at each anchor hue (warning ends up near 0.10).

Full Config

json
{
  "name": "MyBrandSystem",
  "settings": {
    "prefix": "fp",
    "accessibility": "AA",
    "schemes": "both"
  },
  "seeds": {
    "primary": "#4f46e5",
    "secondary": "#c026d3",
    "neutral": "#94a3b8",
    "success": "#22c55e",
    "danger": "#ef4444",
    "warning": "#eab308",
    "info": "#3b82f6"
  },
  "spacing": {
    "mode": "hybrid",
    "base": 4
  },
  "border": {
    "base": 1,
    "scale": [1, 2, 3, 4],
    "gradient": {
      "preset": "none",
      "angle": 135
    }
  },
  "radius": {
    "base": 4,
    "scale": [2, 4, 6, 8, 12, 16]
  },
  "typography": {
    "base": 16,
    "scale": [12, 14, 16, 18, 20, 24, 32, 40],
    "lineHeightFormula": "ratio-1.5",
    "fluid": { "minViewport": 320, "maxViewport": 1280 },
    "fontFamilies": {
      "display": "InterVariable, Inter, system-ui, sans-serif",
      "body": "InterVariable, Inter, system-ui, sans-serif",
      "mono": "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"
    }
  },
  "elevation": {
    "style": "auto",
    "shadowIntensity": 0.12,
    "shadowIntensityDark": 0.4,
    "tintChroma": 0.01
  },
  "interaction": {
    "opacityDisabled": 0.5,
    "durations": { "xfast": 75, "fast": 100, "normal": 150, "slow": 250, "xslow": 400 },
    "focusRing": { "width": 2, "offset": 2, "color": "primary" },
    "scaleActive": 0.98
  }
}

Config Reference

settings

PropertyTypeDefaultDescription
prefixstring"fp"CSS custom property prefix. All tokens will use --{prefix}-*
accessibility"AA" | "AAA""AA"AAA raises the floors the engine solves for: -text reaches 7:1, -border and the icon tier 4.5:1; the matrix text tiers and -contrast reach 7:1 wherever black or white can (on mid-tone steps they keep the better of the two, at least 4.5:1). It also sets the level ThemeEngine.getContrast and the warnings use, and the legacy --fp-contrast-threshold token (0.45 for AAA, 0.6 for AA).
contrastAlgorithm"apca" | "wcag2""apca"How -contrast picks black or white: apca prefers white while it clears 4.5:1, wcag2 takes whichever contrasts more.
schemes"both" | "light" | "dark""both"Which colour schemes the CSS carries. both ships every colour as a light-dark() pair that follows the OS preference or [data-theme]. light or dark ships that scheme alone, with nothing of the other, which makes the default stylesheet 16% smaller for the theme @flexpixels/ui ships (the full one 26%; 27% and 40% with output.legacyFallback). A one-scheme build gives fp-theme-switch and dark islands nothing to switch to.

seeds

Each seed is a hex colour (#RRGGBB or #RGB; an opaque #RRGGBBFF is read too) that generates a 12-step OKLCH scale. For primary, secondary and any semantic seed you set, step 9 of the scale is the seed colour itself.

PropertyRequiredHue AnchorDescription
primaryYes—Main brand colour. Step 9 (buttons, CTAs) is this colour; the other steps take its hue and chroma.
secondaryYes—Supporting brand color. Used for secondary actions, accents, and visual variety.
neutralYes—Structural color — grays, borders, backgrounds, body text. The skeleton of your UI.
successNo145°Positive feedback (confirmations, completed states). Auto-generated if null.
dangerNo25°Destructive actions, errors. Auto-generated if null.
warningNo85°Caution, potential issues. Auto-generated if null.
infoNo250°Informational, neutral context. Auto-generated if null.

An optional surface seed (hex) anchors dark-mode neutral steps 1–5 to a deliberately tinted dark ground — step 1 becomes exactly that colour, blending back to the standard dark ramp by step 6, with light mode untouched.

The engine converts your hex seeds to OKLCH and builds the scale on OKLCH lightness ramps, which are more perceptually even than HSL.

interaction

PropertyTypeDefaultDescription
opacityDisablednumber0.5Disabled-state opacity (0–1)
durations.xfastnumber75Extra-fast transition in ms
durations.fastnumber100Fast transition in ms
durations.normalnumber150Normal transition in ms
durations.slownumber250Slow transition in ms
durations.xslownumber400Extra-slow transition in ms
focusRing.widthnumber2Focus ring outline width in px
focusRing.offsetnumber2Focus ring outline offset in px
focusRing.colorcolor role"primary"Colour role for --fp-focus-ring-color: any of the seven roles. The ring uses that role’s -text colour.
scaleActivenumber0.98Scale on :active press (0–1)

Reduced motion is not a duration: it is handled by the motion switches (see Motion). An old durations.reduced key is accepted and ignored. Easings, state layers, spring and stagger settings are on the Interaction page.

elevation

Controls the shadow model and the four-level shadow ladder. The most used fields:

PropertyTypeDefaultDescription
stylestring"auto"auto (acts as flat), flat, neumorphic, liquid-glass, brutalism
shadowIntensitynumber0.12Light-mode shadow opacity (0–1). Higher = darker shadows.
shadowIntensityDarknumber0.4Dark-mode shadow opacity (0–1).
tintChromanumber0.01Chroma of the shadow tint (0–0.05). 0 = pure grey, 0.05 = vivid.

See Elevation for every style and option.

spacing

PropertyTypeDefaultDescription
mode"linear" | "geometric" | "hybrid""hybrid"Scale generation mode
basenumber4Base unit in logical pixels. Outputs as precomputed rem
scalenumber[]—Custom primitive (--fp-dim-*) scale; replaces the mode’s scale

Spacing modes:

  • "linear" — Even increments (--fp-s-1…12 at base 4: 2, 4, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48px)
  • "geometric" — Faster growth (--fp-s-1…12 at base 4: 1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128px)
  • "hybrid" — Linear for the small steps (tight UI spacing), geometric for the large steps (generous layout spacing). Default and recommended.

The mode also picks the default --fp-dim-* primitive list, unless you give scale.

All spacing primitives are output as precomputed rem values (px / 16). For example, --fp-dim-4 resolves to 0.25rem (4px at a 16px root font size).

radius

PropertyTypeDefaultDescription
basenumber4Base radius in logical pixels. Maps to --fp-radius-base
scalenumber[][2,4,6,8,12,16]Radius primitives (--fp-radius-1 … in logical px)
cornerShapestring"round"Corner character: round, squircle, bevel, scoop, notch, square (see Shape)

The engine also generates --fp-radius-full: 9999px and a semantic --fp-corner-circle alias for full-circle elements like avatars. The scale is written smallest first. By default --fp-corner-control is the base radius, --fp-corner-surface the step nearest base × 2 and --fp-corner-overlay the step nearest base × 3. radius.corners states any of them instead, in px (control also takes "full"): { "control": "full", "surface": 24 } gives pill controls with 24px cards.

border

PropertyTypeDefaultDescription
basenumber1Base border width in logical pixels. Maps to --fp-border-base
scalenumber[][1,2,3,4]Border width primitives (steps 1-4 in logical px)
gradient.preset"none" | "primary-secondary" | "primary-neutral" | "secondary-neutral""none"Gradient preset derived from seed colors
gradient.anglenumber135Gradient angle in degrees (0-360)
gradient.customstring?—Custom CSS gradient value. Overrides preset.

The engine generates a Three-Layer border API:

  • Primitives: --fp-border-1 through --fp-border-4 (from scale), --fp-border-none (0), --fp-border-base (alias to scale entry matching base)
  • Named widths: --fp-border-w-{hairline,thin,medium,thick} (from widthScale)
  • Semantics: --fp-stroke-control (buttons/inputs), --fp-stroke-divider (separators), --fp-stroke-strong (focus rings), --fp-stroke-accent (decorative), --fp-stroke-hairline
  • Gradients: --fp-border-gradient-brand and --fp-border-gradient-subtle always; --fp-border-gradient-active only when gradient.preset is not "none" or gradient.custom is set

Gradient presets use seed-derived CSS variable references so they adapt when seeds change:

json
{
  "border": {
    "base": 2,
    "gradient": {
      "preset": "primary-secondary",
      "angle": 135
    }
  }
}

Components consume border width via --fp-stroke-control. To give a FlexPixels component a gradient border, add the border-gradient attribute; set --fp-border-gradient on it (for example to var(--fp-border-gradient-active)) to choose the gradient.

typography

PropertyTypeDefaultDescription
basenumber16Base font size. Must be 16 — validation rejects anything else.
strictGridbooleantrueEven-integer scale + 2px-snapped line heights. Set false to allow odd sizes (13, 15…).
scalenumber[][12, 14, 16, 18, 20, 24, 32, 40]Font size scale (px). Even integers when strictGrid is true.
lineHeightsnumber[]auto-computedOptional sparse overrides aligned 1:1 with scale; missing entries are filled in by the formula.
lineHeightFormula"ratio-1.5" | "golden" | "compact""ratio-1.5"Algorithm for auto-computed line heights. See table below.
fluidfalse | { minViewport, maxViewport, roles? }{ minViewport: 320, maxViewport: 1280 }Utopia-style clamp() for upper-half-of-scale roles. Pass false to disable globally.
fontFamilies{ display, body, mono }Inter / Inter / "Geist Mono", ui-monospace, …Three family slots. Type styles pick one per role.
fontWeights{ regular?, medium?, semibold?, bold? } (each 1–1000){ regular: 400, medium: 500, semibold: 600, bold: 700 }Named weight primitives. Exactly these four names; any other key is an error.
letterSpacingsRecord<string, string>{ tighter: -0.03em, tight: -0.02em, snug: -0.01em, normal: 0em, wide: 0.04em }Named letter-spacing primitives. Type-style letterSpacing can reference these by key.
metrics{ display?, body?, mono? }Inter / Inter / Geist MonoPer-family font metrics, in the font’s own units. Enables --fp-text-{role}-trim-top/-bottom leading-trim tokens. A slot you set needs all of familyName, unitsPerEm (above 0), ascent, descent, lineGap, capHeight (not above ascent) and xHeight.
comfort{ lineLength?, minSize?, maxLineHeightRatio? }{ 65ch, 1rem, 1.6 }Reading-comfort caps emitted as --fp-text-comfort-*; the fp-prose element applies them.
variableAxes{ wght?, opsz?, slnt? }noneVariable-font axis triples [min, max, default]. Emits --fp-font-axis-* when configured.
scenario"marketing" | "app" | "editorial" | "dashboard"noneCurated bundle of scale + lineHeightFormula + fluid range. Your explicit fields still override.
typeStylesRecord<string, TypeStyleDef>14 built-in rolesPer-role overrides + custom roles. See the MCP resource flexpixels://typography/roles/{role} for the built-in role intent metadata.

Line-height formulas

The engine auto-computes line heights using one of three formulas when lineHeights is omitted:

FormulaMultiplierBest for
ratio-1.51.5×UI (default). Snapped to 2px grid.
golden1.618×Editorial / long-form reading.
compact1.3×Data-dense dashboards and tables.

For the default ratio-1.5 and the 8-step default scale:

Font SizeLine HeightRatio
12px18px150%
14px22px157%
16px24px150%
18px28px156%
20px30px150%
24px36px150%
32px48px150%
40px60px150%

Scenario shortcut

typography.scenario swaps multiple defaults in one line — handy when you know the product type but don’t want to hand-tune scale and leading. See Typography System for the full table.

You can always override with explicit values if your design requires different proportions.


Building your theme

Programmatic (Node or Bun)

ts
import { mkdirSync, writeFileSync } from "node:fs";
import { generateThemeCSS, loadConfigFromPath } from "@flexpixels/cortex";

const config = loadConfigFromPath(`${process.cwd()}/theme-config.json`);
mkdirSync("src/styles", { recursive: true });
writeFileSync("src/styles/theme.css", generateThemeCSS(config));

generateThemeCSS writes the stylesheet output asks for (the lean set by default); generateFullThemeCSS always writes every token. loadConfigFromPath throws on a missing or invalid file; loadUserConfig instead falls back to the default theme. Build & Import covers wiring this into a build and loading the result.

In the browser

The engine also runs in the browser, so you can generate a theme on the fly and swap it in:

js
import { generateThemeCSS, mergeThemeConfig } from "@flexpixels/cortex";

const css = generateThemeCSS(mergeThemeConfig(myPartialConfig));

const style = document.getElementById("fp-theme") ?? document.createElement("style");
style.id = "fp-theme";
style.textContent = css;
document.head.appendChild(style);

Example: dark-only brand

json
{
  "name": "DarkHighContrast",
  "settings": {
    "schemes": "dark",
    "accessibility": "AAA"
  },
  "seeds": {
    "primary": "#818cf8",
    "secondary": "#f472b6",
    "neutral": "#475569"
  },
  "spacing": {
    "base": 8
  },
  "radius": {
    "base": 8,
    "scale": [4, 8, 12, 16, 24, 32]
  },
  "elevation": {
    "shadowIntensity": 0.18,
    "tintChroma": 0.02
  }
}

This produces a dark-only theme with 8px base spacing and larger border radii. accessibility: "AAA" solves -text to 7:1 and -border to 4.5:1, so brand text colours move further from the seed; it also changes the level ThemeEngine.getContrast checks against and the warnings you get. In dark mode the shadow opacity comes from shadowIntensityDark (default 0.4), so shadowIntensity here only matters if you later add the light scheme.


Validation

The config is validated with Zod when it is loaded or merged. Common errors:

Error message (start)Fix
… is not a hex colour / A seed must be opaqueUse #RRGGBB or #RGB for seeds, without transparency
Font size 13px must be an even integer when strictGrid is trueUse 12 or 14, or set typography.strictGrid: false
Line height 19px must be an even integer …Same — use the 2px grid
typography.base must be 16Set typography.base to 16; vary sizes with scale
settings.mode was replaced by settings.schemesRename mode ("system" → "both")

You can validate programmatically:

ts
import { validateThemeConfig } from "@flexpixels/cortex";

try {
  const config = validateThemeConfig(rawInput);
} catch (error) {
  // Zod error with specific field paths
}