---
author: [Teemu Lahjalahti](https://www.linkedin.com/in/teemulahjalahti/)
index: https://salty-css.dev/llms.txt
---
# Salty CSS
> Salty CSS is a framework-agnostic CSS-in-JS library that has focused on developer experience and performance. Instead of providing a heavy runtime bloating the client-side bundle, Salty CSS generates static CSS at build time. The core is written in TypeScript and is framework-agnostic, but there are official integrations for React, Next.js, and Astro. The API has opinions, which is a good thing when trying to do something different and to help understand the decisions made there are concepts pages to explain the reasoning.
Each page has two versions, the normal html version and a markdown text version. While the html version has visually applealing formatting made for humans, the markdown text has designed and normalized formatting for LLMs. See each page's markdown version by appending `.md` to the end of the url. For example, the markdown version of theming concept page is available at [https://salty-css.dev/concepts/theming.md](https://salty-css.dev/concepts/theming.md).
## Concepts
## The Origin Story Behind Salty CSS, Why Salty CSS Exists and Who It’s For

Documentation websites often only focus on explaining *how* the library at hand works. But here I want to tell the story about why Salty CSS was built, what it’s solving and just as importantly, who it isn’t for.
---
#### Salty CSS in plain terms
Salty CSS is an open-source project that helps developers create the styles for a website or web app. Plenty of similar solutions already exist, and Salty isn’t trying to disrupt the CSS tooling ecosystem, it just brings a different set of opinions and learnings, aiming for a good developer experience through type safety, great API ergonomics built for developers, and a lot of built-in features that others might skip. It’s built to work with modern web libraries and frameworks like React, Next.js, and Astro and is best suited for building brand-led websites.
#### The origin story
After years of handcrafting design-led websites, I’d built up a fairly specific idea of how styling could work and, just as much, which tradeoffs I was willing to make to get what I want. I kept watching the ecosystem solve my problems in ways that cut against how I actually wanted to build websites, and a tool that made those tradeoffs the way I’d make them just didn’t exist. I’m Teemu Lahjalahti — Teemukissa to a few people — and Salty CSS is the side project I keep poking at to see how big it can get.
It started after a frustrating day at the office. I found myself on a train to Iisalmi to visit a good friend, opened a new project somewhere along the way to see if I could just make the thing work — and by the time I got back to Helsinki I had a working proof of concept in hand. That’s when it stopped being something to be salty about and turned into a question: what else can I do with this, and how stupid can I get?
#### What shaped it
Two things set this off: a library I loved went away, and the ground underneath it shifted.
The library was [Stitches](https://stitches.dev/) which was a huge inspiration and its death was the original spark to create something new. Its typed, variant-driven **styled** API was simply a joy to use, and when Stitches was discontinued I went hunting for a replacement, worked through the alternatives, and eventually got stupid enough to build my own.
The ground shifting is the bigger half. React Server Components and the swing back to server-first frameworks like Astro put real structural pressure on runtime CSS-in-JS: the old model leaned on React Context for theming and injected styles during render, and in a server-rendered world, where much of your tree never touches a client runtime, that becomes a liability. **Astro pushed me especially hard.** I love building with it, and native, zero-runtime styling that feels at home there is rare; a lot of what I wanted simply didn’t exist.
The ecosystem’s other answers mostly went two ways, if not doing both at the same time — static extraction that analyzes your code without running it, and atomic CSS that optimizes for the tiniest possible stylesheet. Both are legitimate, and keeping a build-time styling tool alive across a churning bundler ecosystem is genuinely hard work that I respect. They just weren’t the directions I wanted to take. I wanted to keep the component-first **styled** API, *share* code within the style files rather than statically analyze them while leaving the imports out, and lean on native browser features for theming and overrides, skipping client side bundle phobias.
CSS Modules weren’t the answer either; I wanted type-safe, reusable components. The **styled** + TypeScript combination lets you build atoms directly, with variants managed as typed props instead of hand-rolled class-name juggling. A brand-led environment shaped every important decision. A lot of the work is about crafting the nicest-looking atoms you can and seeing how they fit together (and trying to scope that kind of detail inside nested utility classes is genuinely painful).
And a fair amount of all of Salty CSS is simply my own opinions. Years of building brand-led websites a certain way plus my own experiments and other open-source projects added up to a fairly specific idea of how styling should feel. Salty CSS was shaped by all of that history and from the fact that I did not want to wait for someone else to *maybe* do something similar in the far future.
#### Where it came from
Salty CSS wasn’t created out of an abstract idea. It formed out of my agency work building brand-led, design-heavy sites — and it’s very much a long running side project of mine, not something tied to any particular company or client.
Much of this work that I have been doing is dependent on dynamic values and logic. The websites I have built are headless-CMS-driven, allowing different possibilities with the same base code and so the same component or molecule has to handle many different cases through a single, consistent variant API. You can’t hardcode every organism and template in advance. To achieve the dynamic layouts for that kind of project, we need an atomic approach and a typed, composable API. For that problem, **styled** plus good TypeScript is the only combination I’ve found that scales cleanly.
I built Salty CSS for myself first and validated it with my own projects; the agency work is simply where the requirements came from. That’s why Salty CSS optimizes for high-fidelity, dynamic, design-led sites rather than for the leanest possible dashboard.
#### Who it’s for, and who it isn’t
I’d rather you pick the right tool than pick mine. So, plainly:
**Salty CSS is a good fit if you’re** building design-led or highly dynamic sites, working server-first with React Server Components or Astro, missing the Stitches-style **styled** DX but unwilling to pay a runtime cost for it, or assembling your own design system from primitives rather than adopting a pre-baked UI kit.
**It might not be the tool if you’re** building lean, repetitive, utilitarian dashboards where the absolute smallest stylesheet is the priority — atomic CSS might genuinely be the better fit there, and I’ll happily say so. And if your team is deep in a legacy runtime CSS-in-JS codebase and not yet thinking in native-web-standards terms, I won’t pretend migration is painless. It isn’t, and I can’t market it as easy. (AI assistants help a lot with the translation work these days, for what it’s worth.)
#### What Salty CSS is right now
*Some honesty about where things stand, so your expectations are calibrated.*
Salty CSS is stable and already used to ship real sites, currently *still* at a pre-1.0 release. I’m not planning major breaking changes before V2 and reaching V1 is largely about committing to proper semantic versioning from now on. It’s been in development since the autumn of 2024, mostly as a side project that gets the most attention when I have proper focus to give to it. And I’m deliberately not in "I am the new industry standard" mindset: the near-term goal is to ship V1, gather more real users, build a community — maybe even new maintainers — heading into V2 and V3.
If you want a reason to start testing it even though it’s largely a one-person project: it’s used to build actual client websites, and real stakes keep it maintained — which is exactly the failure mode that kills so many open-source side projects. I keep it current because I depend on it too. Usually a fix just takes me cracking open a beer and getting it done.
#### Prior art & acknowledgments
Salty CSS didn’t appear from nowhere, and it isn’t trying to win a head-to-head fight with the libraries that shaped it. So, let's give credit where credit is due:
- **Stitches** — the big one, and the closest thing this list has to an old love that got away. Its variant model and the client-side developer experience it delivered were a genuine joy, and honestly its death is what sent me looking in the first place. It isn’t the *single* reason Salty exists, but it’s the feeling Salty will always be chasing.
- **Panda CSS** taught me a lot about approaching server-first styling, and about how to evolve the already-brilliant API Stitches pioneered. You’ll find its fingerprints in Salty on purpose — conventions like `base`, and treating text styles as `templates`, are adopted directly because they’re good ideas.
- **Vanilla Extract** is where the `.css.ts` execution model comes from. The idea that your styles can live in their own files — like the old days — but with the full power of TypeScript was an architectural benchmark.
If one of these fits your project better, use it with my blessing — they’re excellent, and Salty is better for existing alongside them, spicing up the mix. 🧂
While I want to keep Salty CSS as a project with real goals, none of this has to *feel* like a corporate procurement decision to be taken super seriously. The name itself originates from somewhere between an inside pun and the sweaty offices some might call salt mines where any CSS work can feel like a chore for most web developers. So while I’m putting the cat on the table and telling bad jokes, what matters underneath is the engineering — the umami — that’s the real reason anyone should reach for Salty CSS.
---
Concept pages for Salty CSS are created to guide you through the technical details of the compiler, show a scoping model fixing some CSS headaches, iterate a theming mindset into atomic design and introduce why the styled function is my favorite way to create components. I have created these to have a space where I can expand my creative thinking behind Salty CSS and even remember myself why building something on your own has value. Thank you for reading this far, there is still some good stuff coming up!
## How Salty CSS compiler achieves zero-runtime, server-first rendering, and what was the reasoning behind .css.ts files

Building Salty CSS had clear goals. Some of them were inspired how others have approached same issues but and couple came from priorizing different DX that others are going for. While some features have come later, the core of the compiler has stayed largely the same as it's first job was to ensure a build pipeline that would output zero-runtime CSS-in-JS.
---
#### Towards Zero-Runtime
The shift away from runtime CSS-in-JS wasn’t a matter of taste — it was structural. React Server Components (RSC) and server-first architectures like Astro put real pressure on the model that powered the previous generation of libraries: leaning on React Context and client-side CSSOM injection creates genuine friction in a server-rendered world, where much of your tree never touches a client runtime at all.
That said, the term "zero-runtime" has become heavily diluted. Plenty of frameworks that wear the label still ship meaningful orchestration logic to the client, or ask you to work around the edges of static analysis.
Salty CSS takes a particular path through that space. This page demystifies the "magic" behind the compiler: why Salty CSS asks for specific file extensions, how its execution model differs from AST extraction, and what "zero-runtime" actually means here — including the parts where it isn’t literally zero.
#### The Reality of "Zero-Runtime"
To understand Salty CSS, look at what actually ships to the browser.
In a server-first paradigm (like Next.js App Router without `'use client'`, or Astro without `client:load`), **Salty CSS is genuinely zero-runtime**. No style injection, no variant mappers, no theme providers. The HTML arrives with hashed class names, and the static CSS file handles the rest.
But what happens when you *do* need an interactive client component?
Unlike runtime CSS-in-JS, Salty CSS never injects ` next to an element with className={className}
```
Because the same parser runs, JSON-shaped input gets the full Salty surface for free: `{colors.brand}` tokens resolve to the same CSS variables your `styled` components use; `@media`, `&:hover`, and nested selectors all keep working; and two blocks with structurally-identical payloads collapse to a single rule via the shared hash. A CMS block effectively ships "CSS in JSON" and slots straight into your design system — no second pipeline, no escape-hatch global CSS file, and no client styling runtime appearing on the page just because some rules were resolved per-request. The CSS is emitted as a string into the HTML response, and the browser parses it the way it parses your static stylesheet.
Reach for this when content authors want power — give them the parser, not a constrained subset. See the [`defineRuntime` API reference](/react/docs/basics/runtime-styles) for the full surface: signature, feature-support table, scoping, and worked examples.
##### Smart Hashing and Deduplication
The compiler uses deterministic hashing (`toHash`). If a `HeroBlock` and a `TextBlock` independently define identical style objects, they generate the exact same hash. The CSS rules are emitted to the final stylesheet only once, automatically deduplicating your output and keeping the CSS payload minimal.
#### Execution over Extraction (esbuild vs. AST)
To extract styles at build time, a compiler has to understand your code. There are two broad families for doing this, and they make different tradeoffs.
The first is **Abstract Syntax Tree (AST) static analysis**, used to great effect by tools like Panda CSS (and, historically, by Babel-based extractors like Linaria). These are genuinely impressive pieces of engineering — modern static extractors do identifier resolution, constant folding, and partial evaluation, and they’re fast and battle-tested in large codebases.
The tradeoff is inherent to the approach: the analyzer reasons about your code without running it. When a value can only be known at runtime — a prop driven by state, a token resolved through an indirection the analyzer can’t follow, a style object built by a sufficiently dynamic helper — the extractor has to either skip it or pre-generate every plausible combination ahead of time. That’s why static tools offer escape hatches (Panda’s `staticCss`, for instance) to declare the dynamic surface up front. It’s a perfectly reasonable model; it just asks you to keep your styles statically analyzable, and to reach for those hatches when you can’t.
Salty CSS sits in the other family: **it executes rather than analyzes.** Instead of parsing an AST, the Salty compiler uses `esbuild` to actually evaluate your `.css.ts` files in a Node environment during the build step. This is the same fundamental idea Vanilla Extract pioneered with its `.css.ts` model, and Salty owes it a clear debt.
Because the code is genuinely executed:
- You can safely import variables, functions, or design tokens from anywhere in your codebase.
- You can write complex helper functions to generate style objects.
- You can even use `async/await` inside your style definitions (e.g., fetching a remote design token registry during the build).
If your code runs in Node, Salty CSS can compile it. The cost of this approach is the constraint it places on *where* styles live — which is the subject of the next section — but in exchange you don’t have to keep your styling logic statically legible to a parser.
#### The Compilation Pipeline
Knowing *why* Salty CSS executes code rather than parsing ASTs is useful context. Knowing *what actually happens* between saving a file and seeing a styled component in the browser is what you need when something breaks — or when you’re trying to understand why a particular file is slowing your build down.
There are two distinct journeys to trace. The first is the **build-time funnel**: what runs when you start the dev server or kick off a production build. The second is the **load-time funnel**: what the bundler does with a `.css.ts` file when it encounters it as an import, and what the browser ends up with.
##### Funnel 1 — Build time: `.css.ts` → `saltygen/index.css`
```text
Plugin hook → Discovery → Config pass → esbuild (per file) → import() → CSS generation → layer assembly → index.css
```
**1. Plugin hook fires**
The bundler plugin (`saltyPlugin` for Vite, the webpack loader, `withSaltyCss` for Next.js) hooks into the bundler’s `buildStart`. It kicks off a full generation, which begins by wiping `saltygen/` clean and recreating its working subdirectories from scratch. Everything flows from this point on a fresh slate.
**2. File discovery**
A recursive walk of the project tree skips `node_modules` and `saltygen/` entirely. A file counts as salty if its name matches `*.(salty|css|styles|styled).(ts|tsx|js|…)`. Within that set, any file that also calls a `defineX(` factory is additionally flagged as a *config file* and queued for processing first. Two sets leave this step: all salty files, and the config-file subset.
> [!NOTE]
> **Perf:** This is a synchronous depth-first filesystem walk across the whole project. In a large monorepo with thousands of directories, the syscall overhead is measurable. The compiler can’t skip arbitrary output directories — only `node_modules` and `saltygen/` are excluded by name. Keep generated directories out of your source tree, and avoid nesting `.css.ts` files inside paths that share a prefix with other deeply populated directories.
>
> Note: performance optimizations are on the roadmap
**3. Config pass (parallel)**
Config files run before anything else — they declare the design tokens and templates that every component file depends on. Each one goes through the same per-file compile step as everything else (see step 4), and its exports are sorted by what they declare: variables, templates, media queries, fonts, imports, and globals. `salty.config.ts` itself is compiled here as well, and its output is merged in.
The output of this pass is written into `saltygen/`: the global CSS layers (variables, reset, global, templates, fonts, imports), the generated TypeScript token/template/media-query types, and a serialised snapshot of the merged config — tokens, templates, media queries — that later steps can read without re-running the compiler.
**4. Per-file esbuild compilation**
This is the step that makes Salty CSS an *execution-based* compiler, and where build performance is most sensitive.
Before esbuild ever sees the source, two things happen to it. First, any `styled(SomeNonSaltyComponent, …)` call is rewritten to `styled('div', …)`, so non-salty components don’t drag their import chains into the bundle. Second, the cached config is made available to the file at evaluation time, so each file can resolve design tokens without re-compiling the config.
The patched source is then fed to **esbuild via stdin** (not as a file on disk), bundled, tree-shaken, and transpiled to a Node-compatible format. The result is written into `saltygen/js/` under a deterministic, content-derived filename — so an unchanged file produces the same path and can be reused by the incremental HMR path.
> [!NOTE]
> **Perf:** esbuild is written in Go and is extremely fast — but it follows every `import` chain in the file. `packages: 'external'` excludes `node_modules`, but *local* barrel files are a different matter. If your design tokens live in `./tokens/index.ts` and that file re-exports 50 individual token modules, esbuild follows all 50 chains for every `.css.ts` that imports it. Each file gets its own esbuild invocation, so a barrel with 50 re-exports across 80 style files means 4 000 extra module parses. Import from the specific token file you need, not a catch-all barrel.
**5. Dynamic `import()` + export bucketing**
The compiled `.js` is loaded into the running Node process with a dynamic `import()`. This is the step that separates Salty CSS from static AST tools: the code is *executed* — any logic you wrote runs, any imports resolve, any `async/await` settles. The exports come back as a live JavaScript object.
Each named export is then inspected to work out what it is — a keyframes definition, a className generator, or a styled generator — and bucketed accordingly. Exports that resolve asynchronously (a bare `Promise`, or a function flagged to be awaited) are settled before they’re bucketed.
> [!NOTE]
> **Perf:** You *can* `await fetch(...)` inside a style definition to pull tokens from a remote registry at build time. Each unresolved `await` serialises evaluation within that file’s module. If 30 components each independently fetch from the same endpoint, you wait for 30 sequential requests. Batch-fetch once in a shared import and let the other files import the result instead — esbuild will inline the value, and the fetch runs once.
**6. CSS generation**
For each generator, the build-time context is locked in: the export name becomes the CSS filename prefix (`Button` → `cl_button-TzHVd-0.css`) and, in development, the value of the `data-component-name` attribute.
The generator then resolves and serialises its styles — which means it:
- Resolves `{token.path}` references to `var(--token-path)` CSS custom properties
- Expands template call sites (`textStyle: 'heading.large'` → the class that the template layer emits)
- Handles `@media` blocks, pseudo-selectors, and modifier rewrites declared in your config
- Serialises the result to a CSS string
The **hash** is computed from the style content itself — base, variants, and compound variants — not from the export name. It’s content-addressed: rename the export and nothing changes; edit a style value and the hash changes. Two components with structurally identical style objects produce the same hash and collapse to a single CSS rule, deduplicated automatically.
> [!NOTE]
> **Note on cascade order:** A `styled()` call whose first argument is another styled component increments `priority` by one. Higher-priority generators land in a later CSS layer (`l1`, `l2`, …). Because the `@layer` order is declared at the top of `index.css`, the cascade is deterministic: a more-specific component’s rules always win over its base’s rules, regardless of where the files live on disk or what order they were compiled in.
**7. Layer assembly + `index.css`**
Component CSS files are grouped by priority and merged into `l_0.css`, `l_1.css`, and so on — each wrapped in `@layer l0 { … }`. Each per-component block is delimited by `/*start:-*/` and `/*end:*/` markers. These markers are how the HMR incremental path patches a single component’s CSS without triggering a full rebuild.
`index.css` is then assembled as the single entry point: a `@layer imports, reset, global, templates, fonts, l0, l1, …;` declaration at the top, followed by `@import` rules for each global file and each layer file. This is the file the user’s app imports.
---
##### Funnel 2 — Load time: `saltygen/` → rendered component
The build funnel produces the CSS. This second funnel traces what happens when the bundler processes a `.css.ts` *import* in your component tree, and what the browser ultimately receives.
```text
Bundler load hook → source transform → minified client file → browser renders
```
**1. Bundler load hook**
When the bundler encounters a `.css.ts` import, the plugin’s `load` hook fires. For React projects it runs a framework-specific transform that is loaded lazily and memoised for the entire bundler session, so the transform module loads once regardless of how many salty files exist.
**2. Source transform**
The per-file compile step runs again on the file (reusing the cached `.js` from `saltygen/js/` if the content hasn’t changed). For each styled or className export, the generator’s pre-computed client metadata is serialised — `{ hash, variantKeys, propValueKeys, defaultProps, attr }` — and the source is rewritten in place: the full style object is replaced with the baked-in client form.
```ts
// Your source
export const Button = styled("button", {
base: { padding: "{spacing.medium}" },
variants: { intent: { primary: { background: "{theme.primary}" } } },
});
```
```ts
// What the bundler serves to the browser
export const Button = styled("button", "TzHVd", {
hash: "TzHVd",
variantKeys: ["intent"],
propValueKeys: [],
defaultProps: {},
attr: { "data-component-name": "Button" }, // stripped in production
});
```
Import paths are also rewritten: `{ styled } from "@salty-css/react/styled"` becomes `{ styledClient as styled } from "@salty-css/react/styled-client"`. All style logic — the `base` object, token references, variant definitions — is gone from the bundle.
**3. Browser receives**
The client bundle contains no CSS serialisation engine, no CSSOM injection, no theme provider. The HTML element carries hashed class names (`class="TzHVd intent-primary"`). The static `saltygen/index.css` — already linked in `` — provides `.TzHVd { … }` and `.TzHVd.intent-primary { … }`. The browser applies them via its native cascade. Nothing computes anything.
**4. React render — server-first path**
In a React Server Component or an Astro component, there is no client bundle for that component at all. `styledClient` runs on the server, emits a string of class names baked into the HTML, and the component contributes zero JavaScript to the client payload. This is the "genuinely zero-runtime" case from the opening of this page.
**5. React render — client component path**
`styledClient` is the thin mapper that ships to the browser when you mark a component `'use client'`. It receives the pre-compiled client metadata, reads variant props at render time (e.g. `intent="primary"`), and appends the matching class name alongside the base hash class. If any `css-*` props are present (like `css-bg-color="tomato"`), it writes the corresponding CSS custom property as an inline style. No new classes are generated, no `
{children}
);
}
```
In Astro it's the same call in the frontmatter, then `` on a wrapping element — with one caveat about `set:html` in the security section.
###### What comes out
Hand it a style object and you get back a hash and a scoped rule:
```ts
await runtime.resolve({
background: "{colors.brand.main}",
padding: "2rem",
"&:hover": { filter: "brightness(1.1)" },
});
```
```css
/* illustrative — the real hash is generated */
.dLwKs { background: var(--colors-brand-main); padding: 2rem; }
.dLwKs:hover { filter: brightness(1.1); }
```
`resolve` defaults the scope to `.${className}`, which is what you want nearly every time. The class is a **deterministic hash of the style object**, from the same hashing the compiler uses — so two blocks with structurally identical styles produce the same class, and you can collapse them to one rule. More on that in Example 2.
The other two members are there for the times `resolve` is too opinionated. `runtime.css(styles, scope)` takes an explicit scope when you need to target something that already exists — `runtime.css({ color: "{colors.brand.main}" }, "#hero")` emits a rule for `#hero` — and with no scope at all it returns unwrapped declarations you can stitch into a rule you're building yourself. `runtime.className(styles)` is the synchronous hash on its own, for when the CSS for that shape is already on the page and you only need the class to attach.
---
##### Example 2 — Profile customization
The flagship case. Someone picks their colors in a settings panel, you store the result, and their modules render in their look.
###### How you define it
The important move is that **you** build the style object, from fields you decided to expose. The person's data fills in slots; it doesn't arrive as a style object:
```tsx
import { runtime } from "@/lib/runtime";
type ProfileStyle = {
bg: string;
text: string;
accent: string;
radius: string;
};
export async function ProfileModule({
style,
children,
}: {
style: ProfileStyle;
children: React.ReactNode;
}) {
const { className, css } = await runtime.resolve({
background: style.bg,
color: style.text,
borderRadius: style.radius,
padding: "1.5rem",
border: "1px solid {colors.grey.light}",
// nested selectors, exactly as in a styled component
"& a": { color: style.accent, textDecoration: "underline" },
"& h2": { color: style.accent },
// states — the thing an inline style can't do
"&:hover": { boxShadow: "0 2px 12px rgb(0 0 0 / 0.12)" },
// and your named breakpoints, by the same names your components use
"@tabletUp": { padding: "2.5rem" },
});
return (
);
}
```
Notice what's mixed in: `{colors.grey.light}` is your token, sitting in the same object as the person's chosen accent color. The parts of the design you still own stay owned.
###### How you use it
```tsx
const profile = await getProfile(handle); // your data layer
{profile.title}
{profile.bio}
;
```
###### The habit worth copying
**Don't pass a raw object from your database straight to `resolve`.** Map it, field by field, into a shape you wrote. It costs you a type and a few lines, and it buys three things: a much smaller security surface (see below), the freedom to redesign later without every saved profile turning into a broken layout, and an actual answer when someone asks what a "profile style" can contain.
**Dedupe when a page renders many of these.** Because the class is a hash of the object, a hundred modules sharing one look are a hundred identical `}
{/* …block content, rendered by the same components as every other section */}
);
}
```
###### How you use it
The override lives with the content, in whatever shape your CMS or config gives you:
```ts
{
type: "section",
styleOverride: {
background: "{colors.black}",
color: "{colors.grey.light}",
paddingBlock: "3rem",
"@desktopUp": { paddingBlock: "4rem" },
},
// …
}
```
Note the `@desktopUp` in there. Named breakpoints work in a runtime payload exactly as they do in a `styled` component — define them once with `defineMediaQuery`, reference them by `@name` — which means the people or systems writing overrides get your breakpoint vocabulary instead of guessing pixel values. Same failure mode as at build time, too: if a definition never reaches the build, the name silently emits an at-rule that never matches.
The block component is untouched. Every other section still renders the plain `Section`, and the deviation is data — visible where the content lives, deletable in one edit, and not a permanent new axis in your component API.
Two notes on how this lands in the cascade. First, `styled` components accept a `className` at the call site like any React element, which is how the runtime class rides along next to the generated hash. Second — and this is the part that makes overrides actually work — **runtime CSS is emitted without a cascade layer.** Salty's own rules all live in [layers](/react/docs/basics/scoping-and-composition), and in native CSS an unlayered rule outranks every layered one regardless of specificity. So the override wins over the component's own styles with no specificity fight, no `priority` bump, and no `!important`.
That's exactly what you want for a deliberate one-off, and exactly why you shouldn't reach for this casually: a runtime rule sits above your entire layer hierarchy by construction. It's a trump card, not a tiebreaker.
If you'd rather target something that already has a selector — a global id, an element you don't wrap — use `runtime.css(styles, "#hero")` and skip the class entirely.
---
##### What comes along, and what doesn't
Because it's the same parser, most of Salty's authoring surface works unchanged. The exceptions are the things that need either a component wrapper or a place in the static stylesheet — `defineRuntime` returns strings, not components, and its output lives in a per-request `` in the middle of a generated rule is HTML injection, and that path ends where you'd expect it to.
So: not remote code execution, and more than nothing. Treat a style payload roughly the way you'd treat user-supplied HTML you're about to render.
---
##### Runtime styles
[`defineRuntime`](/react/docs/basics/runtime-styles) is the one API that takes a style object at request time and turns it into real CSS — from a CMS field, a database row, whatever somebody saved in a settings panel three minutes ago. **It does not sanitize what you hand it.** Property values pass through as text.
Not sanitizing *silently* is a deliberate choice rather than a gap I'm hoping you won't notice. A filter strict enough to be genuinely safe would block a good share of what this API exists for, and one loose enough to stay out of the way would mostly sell you confidence you hadn't earned. So the validation boundary is yours — which is the right place for it anyway, because you're the one who knows whether a payload came from a colleague with a CMS login or from an anonymous signup form.
What that doesn't rule out is help. Some kind of opt-in validation helper is likely to land at some point — something you call, with a shape you chose, rather than something that quietly filters your styles behind your back. Until it does, and honestly after it does too, the code below is the pattern.
###### How you define it
Don't hand a stored object to the parser. Write the shape you support, validate into it, and let that be the only way data becomes style:
```ts
// a plain .ts file
const HEX = /^#[0-9a-f]{6}$/i;
const RADII = ["0", "4px", "12px", "999px"];
export type ProfileStyle = { bg: string; text: string; radius: string };
export function toProfileStyle(row: Record): ProfileStyle {
const hex = (v: unknown, fallback: string) =>
typeof v === "string" && HEX.test(v) ? v : fallback;
return {
bg: hex(row.bg, "#ffffff"),
text: hex(row.text, "#111111"),
radius: RADII.includes(row.radius as string) ? (row.radius as string) : "12px",
};
}
```
Three fields, two shapes, a fallback each. Everything not on that list is not a thing a profile can be.
###### How you use it
```tsx
const style = toProfileStyle(profile.style);
const { className, css } = await runtime.resolve({
background: style.bg,
color: style.text,
borderRadius: style.radius,
padding: "1.5rem",
border: "1px solid {colors.grey.light}",
});
```
The person picked three values. They did not pick which properties exist — so `background-image: url(…)` was never on the table, and neither was anything else. Do this one thing and most of this page stops applying to you.
Four details around the edges of that API:
- **The `scope` argument is a selector.** `runtime.css(styles, scope)` writes it straight into the stylesheet, so untrusted text there escapes the rule and gets to write its own. Scopes come from your code, always.
- **Mind the raw-HTML sinks.** The risk isn't putting CSS in a `` child isn't a raw sink; Astro's `` is one by definition — and it's also the correct way to render runtime CSS there, which means the safety has to come from the payload being one you built. Same story for `dangerouslySetInnerHTML` if you ever reach for it here.
- **Cap the size.** An untrusted payload decides how *much* CSS you generate, not just what it says. A deeply nested object is a slow request and a fat page for every visitor who loads it. Validate length and depth alongside values.
- **Know which threat model you're in.** Ten editors on an internal CMS and a public profile page behind an open signup form are the same API and completely different risks.
The [Runtime styles](/react/docs/basics/runtime-styles) page covers the rest of that API. If you're building the profile-customization case, read this section again when it stops being theoretical.
---
##### Prop tokens
The rung below runtime styles is a prop token: `{props.X}` in a style, a `css-x` prop at the call site, one static rule and a CSS variable carrying the value. It's much narrower by construction — the value rides an inline custom property into a rule you already wrote, so a user can fill a slot but can't add a property. That's exactly why it's the right tool for a user-chosen colour, and [Dynamic Values](/react/docs/basics/dynamic-values) is the page for it.
Narrower isn't closed, though:
```tsx
```
If the compiled rule is `background: var(--props-bg)`, then a value of `url(https://example.test/pixel.png)` is a perfectly valid, perfectly well-escaped CSS value — and now every visitor's browser makes a request to a host somebody else picked. Nothing was injected and nothing was malformed. The value simply did what CSS values are allowed to do.
So validate the shape you actually meant, at the boundary, the same as anywhere else — a colour prop against a colour pattern, a size against a list. And when the set of looks is genuinely closed, don't take a free-form value at all: five named looks are a `conditional` token group and one attribute in the markup, with no user-supplied values anywhere in the picture. [Theming](/react/docs/basics/theming) is the better tool whenever the answer is enumerable.
The same reasoning covers the plain `style` prop and any custom property you let a user fill directly.
---
##### CSS from somebody else's server
`defineImport("https://…")` and hosted font sheets pull CSS you didn't write into your page, and imported CSS has exactly the same powers as the CSS above. Two consequences worth being deliberate about: whoever runs that host can change the file's contents at any time and your build will never notice, and every visitor's browser tells that host the visit happened — IP, user agent, referrer. If you have privacy commitments about third-party requests, a font stylesheet is one.
Self-host when you reasonably can. Vendor the file into your repo and `defineImport("./vendor/thing.css")`, or register fonts from local files with [`defineFont`](/react/docs/basics/fonts). When you do keep a remote sheet, keep it to hosts you'd happily name in a code review — and note that `@import` can't carry an integrity hash — Subresource Integrity only covers `