@csszyx/dynamic — Runtime CSS Injection
@csszyx/dynamic enables sz-style objects from external sources (JSON config, API
responses, CMS, form renderer schemas) to be applied at runtime. CSS is injected only for
classes not already present in the pre-built stylesheet.
When to use
Section titled “When to use”dynamic() is an escape hatch, not a default. It is the only csszyx helper
that generates CSS at runtime (it injects rules into the page on the fly), so
it carries a real cost the build-time path does not: runtime work, a larger
runtime bundle, a security surface for untrusted input, and its classes are not
mangled. Reach for it only when the build genuinely cannot know the styles
ahead of time:
- ✅ Use
dynamic()when the style values come from runtime data you don’t control at build — a JSON theme, an API response, user config, a CMS:sz={{ w: valueFromServer }}. - ✅ Or, rarely, when a style genuinely cannot be expressed with the build-time
helpers (
sz/szv/szr/szcn). This is uncommon — most “dynamic-looking” cases are actually a fixed set of options, whichszv()covers at build time. - ❌ Do not use
dynamic()for styles written in your source, conditional styles, or a known set of variants — those are all build-time. A literal likesz={{ p: condition ? 4 : 2 }}andszv()variants are extracted and safelisted at build with zero runtime CSS injection.
Default to build-time. If a value is a literal or a finite set of choices, it
belongs in sz / szv — not dynamic().
| Use case | Approach |
|---|---|
| Styles defined in source code | sz prop (build-time, zero runtime) |
| Conditional / variant styles (finite, known) | szv() + sz array syntax (build-time) |
Resolving szv output to a className by hand | szr() (build-time-safe, mangle-aware) |
| Styles from JSON / API / user config (unbounded) | @csszyx/dynamic (runtime injection) — escape hatch |
Install
Section titled “Install”npm install @csszyx/dynamic# or use the umbrella:npm install csszyx # csszyx/dynamic is includedFramework-agnostic
Section titled “Framework-agnostic”import { dynamic } from '@csszyx/dynamic';// or:import { dynamic } from 'csszyx/dynamic';
const cls = dynamic({ p: 4, bg: 'blue-500', hover: { bg: 'blue-600' } });// → "p-4 bg-blue-500 hover:bg-blue-600"// CSS for missing classes is injected into the page automatically.
// `as const` objects are supported — no `as any` cast neededconst style = { p: 4, bg: 'blue-500' } as const;const cls2 = dynamic(style); // ✅React hook — useSz()
Section titled “React hook — useSz()”import { useSz } from '@csszyx/dynamic/react';// or:import { useSz } from 'csszyx/dynamic/react';
function DynamicCard({ style }: { style: SzObject }) { const { sz } = useSz(); return <div className={sz(style)} />;}useSz() wraps dynamic() and memoises results by input object identity.
React hook — useDynamicScope()
Section titled “React hook — useDynamicScope()”For components that inject classes for a bounded lifetime (e.g. a form renderer widget that unmounts when the form closes):
import { useDynamicScope } from '@csszyx/dynamic/react';
function FormWidget({ schema }) { const { sz, cleanup } = useDynamicScope();
useEffect(() => { return cleanup; // injected stylesheets removed on unmount }, [cleanup]);
return <div className={sz(schema.style)} />;}The manifest, and why it is off by default
Section titled “The manifest, and why it is off by default”@csszyx/dynamic can fetch /csszyx-manifest.json to check which classes are
already in the pre-built stylesheet and skip injecting duplicates. The build does
not emit that file unless asked:
...csszyx({ build: { emitManifest: true } })Leaving it off is safe. A missing manifest means dynamic() treats nothing as
pre-built and generates its own rules, so the rendered styles are identical —
what changes is bytes.
And bytes are the reason for the default. The manifest lists the whole class
census, while dynamic() only asks about the classes it actually renders.
Measured on a 668-class census (pnpm bench:dynamic-manifest), the file costs
about 2 kB gzipped no matter what, while injecting the classes a
10%-runtime app renders costs about 500 B. It only comes out ahead once most of
the app is styled at runtime.
Not sure which side your app is on? Measure it:
import { dynamicReport } from '@csszyx/dynamic';
// after the app has exercised the paths that matterconsole.log(dynamicReport().summary);// "Manifest cost 2078 B and spared only 340 B of injected CSS —// set build.emitManifest to false."Delta injection — only missing CSS
Section titled “Delta injection — only missing CSS”On each dynamic() call:
transform(szProps)→ Tailwind class string (same logic as the build-time compiler)- Each class is looked up in the manifest, when one was loaded:
- In manifest → use the resolved name (mangled in production builds)
- Not in manifest, or no manifest → generate CSS rule + inject into a
CSSStyleSheettier
- Return the final class string
This means a <div className={sz({ p: 4 })} /> inside a form renderer widget that is
also using p-4 in the main app will reuse the existing CSS — no duplicate rule injected.
A shadow’s size is not generated by dynamic() yet: Tailwind writes the theme’s
shadow into the class at build time and defines no --shadow-* variable a rule in
the browser could read, so { shadow: 'sm' }, { shadow: { size: 'sm', op: 50 } },
dropShadow: 'md' and their inset and text forms get no working rule from it. The
class still works when the build’s Tailwind generated it — the manifest, or the
same class used statically anywhere in the app. A shadow colour, with or without an
opacity (shadowColor: { color: 'black', op: 50 }), is generated as usual.
What a generated rule covers
Section titled “What a generated rule covers”A rule dynamic() writes itself is the rule Tailwind writes for the same class, for the
values these docs show on a key. Some edges are worth knowing before you rely on it.
Tailwind versions. The rules are written as Tailwind 4.3.3 writes them, and checked
to mean the same on every version from 4.0.0 to 4.3.3. A key Tailwind added later
than 4.0 still gets a rule at runtime on an older project, where the same value written
statically has none: borderBs and borderBe need Tailwind 4.2. dynamic() does not know
which Tailwind your project installed.
Theme variables. A rule names the theme’s variable, var(--color-red-500) for
bg: 'red-500'. Tailwind writes a theme variable into your CSS only when a class in the
build uses it, so a colour or a size that only dynamic() uses has no value. In
development the console names the variable (dynamic-rule-inert). Import Tailwind with
every theme variable written to fix it for the whole app:
@import "tailwindcss" theme(static);Variants follow your stylesheet. The csszyx plugin reads how your project’s Tailwind
writes each variant and hands that to dynamic(), so a rule it writes wraps the class
the way your build does:
- your breakpoints and container sizes, with their values and their order, including a
theme that replaces the defaults (
--breakpoint-*: initial); - your
@custom-variants, adarkyou redefined (&:where(.theme-dark, .theme-dark *)) and a redefinedhoverincluded; !importanton every declaration when you import Tailwind withimportant, and each rule in the layer your utilities are in, so it is ordered with the built ones;- your
prefix(...)on every class it returns.
group-*, peer-*, not-*, has-* and in-* work with any of those variants that select
on the element, in a mangled build too, whether the group or peer marker comes from sz
or from dynamic().
hover: is written inside @media (hover: hover), as Tailwind 4 writes it, so a tap on a
touch screen leaves no hover style on. Rules go in at the place Tailwind gives them, so
focus: wins over hover: and md: over sm: whatever the order of your keys.
Built and runtime classes of one call resolve as the build resolves them. In
dynamic({ p: size, md: { p: 8 } }) the build already has md:p-8, and the runtime
p-[13px] still gives way to it from md up. A runtime class takes precedence over a
built class of the same variant, and over a class from outside the call:
cn('md:p-8', dynamic({ p: size })) keeps the runtime padding at every width. Keeping
both in the one call keeps the breakpoint.
Without the plugin (a plain script, a test without a build), dynamic() writes Tailwind’s
default breakpoints, state variants and group-*, peer-*, not-*, has-* and in-* over
them, and dark: in Tailwind’s default
@media (prefers-color-scheme: dark). A project that switches dark mode with a class
gets its own dark from the plugin. Tailwind has no light: variant, and neither does
dynamic(): light:p-4 writes no rule and reports dynamic-unsupported, as the build
writes no CSS for it. Declare @custom-variant light (…); in your stylesheet and the plugin
hands it to dynamic() with the rest.
before: and after: write no rule in dynamic(), with or without the plugin: Tailwind’s
rule for them also sets content from a property it declares for the whole page, and a
runtime rule cannot rely on it. Write those classes as literals, so the build lowers them.
A project with two Tailwind stylesheets that declare different variants (another dark,
other breakpoints) has no one set to hand over: the build says so once, and dynamic()
keeps the defaults. Declare the same variants in each, or name the stylesheet your pages
load in tailwindStylesheet.
To keep a class-based dark: or light: (the default up to 0.18.0, .dark .dark\:p-4 and
.light .light\:p-4), build with the plugin and declare
@custom-variant dark (&:where(.dark, .dark *)); and
@custom-variant light (&:where(.light, .light *)); in your stylesheet.
A variant whose name starts with a utility’s prefix and - (w-hover, text-big) gets no
rule, and the build says so once: a value written after that prefix
(w: 'hover:fixed', which lowers to w-hover:fixed) would otherwise pick the variant.
A class it has no rule for writes nothing, and development names each such class
once, up to a limit (dynamic-unsupported). Run __csszyx_dev.reports() in the browser
console to list the session’s reports, the ones the console did not print included
(Public API). For a runtime value on
such a property, keep the property fixed in css: and pass the value as a CSS variable, so the build writes the rule and the value
changes without a new one:
<div sz={{ css: { 'background-blend-mode': 'var(--blend)' } }} style={{ '--blend': mode }}/>Build-time extraction (Layer-1 prescan)
Section titled “Build-time extraction (Layer-1 prescan)”When dynamic() receives a static literal or a module-level const reference,
the compiler extracts all classes at build time and adds them to the Tailwind safelist.
Tailwind pre-generates the CSS — no runtime injection needed.
// Static literal — classes extracted at build time<div className={dynamic({ w: 7, h: 8, rounded: 'sm' })} />
// Const reference — compiler resolves it automaticallyconst boxStyles = { w: 7, h: 8, rounded: 'sm' } as const;<div className={dynamic(boxStyles)} />This is especially useful in Astro SSR without client:* — the CSS is already in the
built stylesheet, so dynamic() finds the classes in the manifest and returns them with
zero CSSOM work.
For truly runtime-dynamic values (variables, API data), the standard browser injection path applies as normal.
SSR safety
Section titled “SSR safety”On the server, dynamic() returns class names without touching CSSOM. There is no
document access in SSR environments.
Manifest generation
Section titled “Manifest generation”The Vite and Webpack plugins write the manifest when the build asks for it, with the same option on both. See why it is off by default before you turn it on.
import csszyx from 'csszyx/vite';
export default defineConfig({ plugins: [...csszyx({ build: { emitManifest: true } }), tailwindcss(), react()],});With build: { emitManifest: true }, the manifest file
(csszyx-manifest.json) is written to the build output so it is served as a
static asset. Without it — the default — nothing is emitted and dynamic()
injects its own rules.
Use with form renderers (RJSF, Formily, etc.)
Section titled “Use with form renderers (RJSF, Formily, etc.)”// Store sz style in JSON schemaconst schema = { uiSchema: { 'ui:sz': { bg: 'white', p: 4, hover: { bg: 'gray-50' }, dark: { bg: 'gray-900' } } }};
// Apply at render timefunction RenderedField({ uiSchema }) { const { sz } = useSz(); return <div className={sz(uiSchema['ui:sz'])} />;}This is the primary target use case: form renderers that store component definitions in
JSON and need hover:, dark:, responsive: variants from user-supplied config.
Untrusted sz — clean it with purifySz
Section titled “Untrusted sz — clean it with purifySz”When the sz object comes from a source you don’t fully control (a CMS, a saved
user theme, any JSON you didn’t author), pass it through purifySz before
dynamic() / useSz. It is allowlist-based: it keeps only keys csszyx
recognizes, drops values that aren’t safe CSS, blocks prototype-polluting keys,
and bounds nesting depth.
import { dynamic, purifySz } from '@csszyx/dynamic';
const className = dynamic(purifySz(untrustedSzFromJson));// Report what was dropped, and relax the default strict mode if you need url()/image-set()purifySz(input, { strict: false, onDrop: (path, reason) => console.warn(`dropped ${path}: ${reason}`),});It also drops a key that writes a selector or an at-rule ('[&>*]', '[@media_print]'):
from untrusted data, that key would choose the selector of every class under it. A key
with a bracket parameter is kept only as csszyx writes it: 'data-[state=open]',
'has-[:checked]', 'aria-[busy]', with letters, digits, - and _.
Compiled or hand-authored sz from your own code does not need purifySz —
use it only at the untrusted boundary. See the
security guide for why the dynamic path is treated as an
untrusted sink.