--- 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 ![Birch tree's trunk reaching towards the sky](https://salty-css.dev/_astro/origins.DerbAe0f.jpg) 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 ![Techy structures in a dark venue](https://salty-css.dev/_astro/compiler.DrQaHZdJ.jpg) 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 ` {children} ); } ``` 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 `` against a `style-src 'nonce-…'` policy. Worth flipping around, though, because CSP isn't only a thing to accommodate here — it's also the best mitigation available for the section above. A payload's `url()` can only phone home to a host your policy allows, so if you're shipping user-supplied styles at all, tighten `img-src`, `font-src` and `connect-src` to the origins you actually use. It's a layer rather than a fix — clever people keep finding side channels that need no network request at all — but it turns a quiet exfiltration into a blocked request and a violation report, which is a much better day. One dev-mode caveat, because it costs people an afternoon: bundler dev servers usually inject CSS through JavaScript instead of serving the built file. A CSP violation that only shows up in development and never in a production build is usually that, not you. --- ### Guides #### Updates Salty is pre-1.0, and every `@salty-css/*` package ships on the same version number. So keeping a project current isn't a per-package chore — it's one command, and that command is most of what this page has to say today. It'll grow. Once there are breaking changes that need a written path through them, the codemods and the this-moved-here's-where-it-went notes land on this page. Worth separating from its neighbour: [Migration](/react/docs/guides/migration) is about moving onto Salty from something else, this one is about moving from one version of Salty to the next. --- ##### Updating the packages `update` — alias `up` — bumps every Salty package in your `package.json` together: ```bash npx salty-css up # everything to latest npx salty-css up 0.4.2 # or pin them all to one version ``` Together is the important word. `@salty-css/core`, `@salty-css/react` and your bundler plugin are built and released as a set, and mixing versions across them produces confusing failures rather than clear ones — a component that renders with no styles, a token path that type-checks and compiles to nothing. Bumping one of them by hand is the shortest route to an afternoon you hadn't planned on. | Argument / flag | What it does | | :-- | :-- | | `[version]` | The version to move to. Defaults to `latest`. | | `--dir ` | Project directory to rebuild once the install finishes. | | `-y`, `--yes` | Skip the confirmation prompt. | | `--legacy-peer-deps` | Passed straight through to npm. Not recommended — it quiets a version conflict rather than resolving one. | One thing to know about what happens after the install: `saltygen/` is a build artifact, regenerated from scratch on every compile, so it wants a fresh build from the new compiler. `--dir` takes care of it, and so does starting your dev server. If you're not sure what you're actually running, `npx salty-css --version` prints the CLI version plus every Salty package in your `package.json`. That's also the output worth pasting in when you open an issue. --- ##### Where the release notes live Every release is written up on [GitHub Releases](https://github.com/margarita-form/salty-css/releases) — what changed, what moved, and anything you need to do on your side. That's the canonical list, and this page won't try to duplicate it. The honest framing of pre-1.0: minor APIs can still move between releases. Pin your versions rather than floating on a caret, read the notes before you bump, and you'll be fine. --- #### Migration Moving an existing codebase onto Salty CSS is two questions, and it's worth answering them in order. First: what has to change structurally, regardless of what you're leaving behind. Second: what does each API you use today actually turn into. The first half of this page applies to everyone — the same six changes land whether you're coming from a runtime CSS-in-JS library, an atomic framework, or a folder of SCSS partials. The second half is per-source: the common API mappings, one worked translation each, and the specific part that tends to be hardest. I won't pretend migration is painless. It isn't, and I can't market it as easy. What I can do is tell you exactly what you're signing up for before you start. (AI assistants help a lot with the mechanical translation these days, for what it's worth — and most of this work is mechanical.) ##### Versions this page assumes APIs move. Everything below was written against these: | Coming from | Version assumed | Note | | :-- | :-- | :-- | | styled-components | 6.4 | `createTheme`, RSC support, transient props | | Stitches (`@stitches/react`) | 1.2.8 | Last published April 2022 | | Panda CSS | 1.11 | 2.0 is in beta at the time of writing | | Linaria | 8.x | wyw-in-js 2, Node ≥ 22.12, `@wyw-in-js/babel-preset` | | Tailwind CSS | 4.3 | CSS-first `@theme` config | | Sass (dart-sass) | 1.102 | Module system (`@use` / `@forward`) | | **Salty CSS** | **0.4.x** | Pre-1.0 — see Compatibility | If you're on an older major of any of these, the mapping tables still hold; the surrounding APIs may not. --- ##### What changes no matter where you're coming from Six things. None of them depend on which library you're leaving. **1. Styles move into their own files.** Salty only compiles files ending in `.css.ts`, `.css.tsx`, `.salty.ts`, `.styled.ts` or `.styles.ts`. If you're coming from styled-components, Stitches, Linaria or Panda's JSX factory, you've been co-locating styles inside `.tsx` — and you give that up. This is a real tradeoff, not a free win. What the boundary buys is a compilation firewall: the compiler only evaluates files that contain CSS, so build cost scales with how much styling you have rather than with the size of your app. **2. CSS text becomes style objects.** Tagged templates and `.scss` blocks both become objects with camelCase keys. `background-color` is `backgroundColor`, `&:hover { … }` is `"&:hover": { … }`. This is the largest chunk of the work by volume and the least interesting — nesting, pseudo-selectors, media blocks and `&` all survive the trip intact. **3. Values resolve at build time.** This is the conceptual change, and it's the one that generates actual decisions rather than typing. Anything your styles currently compute during render has to move onto a ladder, and you stop at the first rung that fits: - The browser already tracks it (hover, focus, checked, valid) → a pseudo-selector in `base` - It's a closed set of outcomes → a **variant**, typed as a prop - It's an open-ended value the consumer picks → a **prop token**, `{props.x}` in the style and `css-x` at the call site - It genuinely doesn't exist until the request runs (CMS payload, tenant config) → [`defineRuntime`](/react/docs/basics/runtime-styles) - It changes per frame → a plain `style` prop, same as always **4. The cascade is `@layer`, not specificity.** Salty declares `imports, reset, global, templates, fonts, l0…l8` and resolves conflicts by layer order. Extending a styled component bumps it into the next layer automatically, so an override wins without a more specific selector. `priority` is the manual control. If your current codebase leans on selector weight or `!important` to settle fights, that machinery doesn't come with you — and `!important` inverts layer order, which is native CSS behaviour rather than a Salty quirk. **5. Theming stops being a JavaScript object.** No provider, no context, no re-render. Conditional tokens compile to `[data-theme="dark"] { --theme-bg: … }` in the static stylesheet, and switching means setting one attribute on an ancestor. Whatever sets that attribute is the whole integration. **6. The requirement is a bundler, not a framework.** Salty needs Vite or Webpack. `styled` ships per framework (React and Astro today); everything else — tokens, templates, media queries, fonts, keyframes, global styles, `className` — is framework-agnostic. See [Framework agnostic APIs](/react/docs/guides/framework-agnostic). ###### What doesn't have to change Nothing about this is a flag day, and the migration is designed to be boring for that reason. Salty's output is regular CSS in its own cascade layers, so it coexists with whatever you already have — CSS modules, hand-written stylesheets, a utility framework, a runtime CSS-in-JS library still rendering half your app. Add the plugin, write one `*.css.ts` file, ship it, and keep going. The two stylesheets don't fight; they sort by layer. Two config options are worth setting *during* the migration specifically: - **`strict: 'warn'`** — mistyped token paths surface as warnings instead of failing the build while you're mid-port. Flip it to `true` when you're through. - **`importStrategy`** — leave it at `'root'` unless you already have route-level CSS splitting you want to preserve. --- ##### The four categories Where you're coming from predicts the shape of the work more than the library name does. | Category | Libraries | The change | The hard part | | :-- | :-- | :-- | :-- | | **Runtime CSS-in-JS** | styled-components, Stitches, Emotion | Execution model: render time → build time | Every function interpolation needs a decision | | **Build-time CSS-in-JS** | Panda CSS, Linaria, Vanilla Extract | Mostly syntax; the model already matches | Output shape (atomic vs. component-hashed) | | **Atomic / utility-first** | Tailwind, UnoCSS | The unit of styling itself | It's a re-architecture, not a translation | | **Preprocessors & plain CSS** | Sass, Less, CSS Modules | Syntax, plus real scoping | Giving up cross-component selectors | Read that table as effort estimation. The build-time CSS-in-JS row is the cheapest migration on the page because the mental model transfers wholesale — you already write styles in TypeScript, you already accept a build step, you already know not to touch `window` in a style file. The atomic row is the most expensive, and it's the one where I'd stop and check the fit before doing any work at all: if you're building lean, repetitive, utilitarian UI where the smallest possible stylesheet is the priority, atomic CSS is a genuinely good architecture for that and this migration may not be worth doing. --- ##### Runtime CSS-in-JS ###### styled-components 6.4 styled-components is the OG `styled` API. The component-first mental model carries over almost completely: `as`, wrapping third-party components, extending a styled component, keyframes and global styles all have direct equivalents. What doesn't carry is the tagged-template syntax, the function interpolations, and the runtime itself. Worth being precise about how close these two are in 2026, because the gap narrowed from both sides. styled-components 6.4's `createTheme` already compiles tokens to CSS custom properties (`var(--sc-colors-fg, …)`) and it has a React Server Components story, so "theming needs a provider" and "it can't run on the server" are both out of date. The remaining difference is *where the work happens*: styled-components resolves styles at render and ships a styling engine to do it (their README puts the package under 13kB gzipped); Salty resolves at build and ships class names. | styled-components 6.4 | Salty CSS | | :-- | :-- | | `styled.div`…`` | `styled("div", { base: { … } })` | | `styled(Component)`…`` | `styled(Component, { base: { … } })` | | `${p => p.$primary ? a : b}` | `variants` — a closed set | | `${p => p.width}px` | `{props.width}` token + `css-width` prop | | Transient props (`$primary`) | Not needed — variant props are consumed by default | | `ThemeProvider` + `props.theme` | `defineVariables` `conditional.theme` + `data-theme` | | `createTheme` | `defineVariables` | | `createGlobalStyle` | `defineGlobalStyles` | | `keyframes`…`` | `keyframes({ … })` | | `css`…`` shared block | `defineTemplates`, or a plain exported object | | `.attrs({ type: "password" })` | `defaultProps` | | `as` prop | `as` prop | | `shouldForwardProp` | `passProps` — inverted: opt-in rather than opt-out | ```tsx import styled from "styled-components"; const Button = styled.button<{ $primary?: boolean }>` padding: 0.6em 1.2em; border-radius: 6px; border: 2px solid palevioletred; background: ${(p) => (p.$primary ? "palevioletred" : "white")}; color: ${(p) => (p.$primary ? "white" : "palevioletred")}; &:hover { filter: brightness(1.05); } `; // ``` ```ts import { styled } from "@salty-css/react/styled"; export const Button = styled("button", { base: { padding: "0.6em 1.2em", borderRadius: "6px", border: "2px solid palevioletred", background: "white", color: "palevioletred", "&:hover": { filter: "brightness(1.05)" }, }, variants: { primary: { true: { background: "palevioletred", color: "white" }, }, }, }); // ``` Two things happened there that are typical of the whole migration. The `$` prefix disappeared, because Salty consumes variant props before they reach the DOM by default — `passProps` is how you opt back out for the cases that need it. And two separate ternaries collapsed into one variant, which is the shape most `props =>` interpolations take once you look at them squarely. **The hard part is the interpolations, not the CSS.** The declaration blocks translate themselves. Every `${props => …}` is a decision on the ladder from the section above, and the count of those in your codebase is a far better estimate of migration effort than the line count is. ###### Stitches 1.2.8 This is the closest API in the list, and that isn't a coincidence — Salty's variant model is deliberately modelled on Stitches', which the [design philosophy page](/concepts/design-philosophy) covers. `variants`, `compoundVariants` and `defaultVariants` are the same names with the same semantics, compound variants use the same `css` key, and named media queries work the same way. Two syntax deltas do most of the work. Base styles nest under `base` rather than sitting at the top level of the config object, and token references change from `$colors$brand` to `{colors.brand}`. | Stitches 1.2.8 | Salty CSS | | :-- | :-- | | `styled("button", { …base, variants })` | `styled("button", { base: { … }, variants })` | | `$colors$brand` / `$brand` | `"{colors.brand}"` | | `createStitches({ theme })` | `defineVariables` | | `createStitches({ media })` | `defineMediaQuery` | | `createTheme()` → class name | `conditional.theme` → `data-theme` attribute | | `css({ … })` | `className({ base: { … } })` | | `utils` | Function templates — see below | | `compoundVariants` / `defaultVariants` | Same | | `as` prop | `as` prop | ```ts import { styled } from "./stitches.config"; export const Button = styled("button", { padding: "0.6em 1.2em", borderRadius: "$radii$md", variants: { tone: { solid: { background: "$colors$brand", color: "white" }, ghost: { background: "transparent", color: "$colors$brand" }, }, size: { small: { fontSize: "0.85rem" }, large: { fontSize: "1.15rem" } }, }, compoundVariants: [{ tone: "solid", size: "large", css: { fontWeight: 700 } }], defaultVariants: { tone: "solid", size: "small" }, }); ``` ```ts import { styled } from "@salty-css/react/styled"; export const Button = styled("button", { base: { padding: "0.6em 1.2em", borderRadius: "{radii.md}", }, variants: { tone: { solid: { background: "{colors.brand}", color: "white" }, ghost: { background: "transparent", color: "{colors.brand}" }, }, size: { small: { fontSize: "0.85rem" }, large: { fontSize: "1.15rem" } }, }, compoundVariants: [{ tone: "solid", size: "large", css: { fontWeight: 700 } }], defaultVariants: { tone: "solid", size: "small" }, }); ``` Everything below `variants` is byte-identical. That's the whole Stitches migration for a typical component. **`utils` is the one that needs thought.** A Stitches util maps an invented property name to several declarations, taking an arbitrary value — `mx: (value) => ({ marginLeft: value, marginRight: value })`. The equivalent is a [function template](/react/docs/basics/templates): same idea, defined once in `defineTemplates`, applied as a key inside `base`, with the argument typed. ```ts export default defineTemplates({ mx: (value: string) => ({ marginLeft: value, marginRight: value }), }); // base: { mx: "1rem" } ``` If your utils do property *renaming* with no logic, that's a template. If they rewrite values by pattern — a `px → rem` shorthand, a spacing scale that does arithmetic — that's a [modifier](/react/docs/basics/modifiers) instead. --- ##### Build-time CSS-in-JS ###### Panda CSS 1.11 There's shared vocabulary here on purpose: `base` and treating text styles as templates are both conventions Salty took from Panda because they're good ideas. So a fair amount of a Panda codebase reads as valid Salty with the imports swapped. Four things genuinely differ, and two of them are architectural. **Extraction model.** Panda statically analyses your source to find style calls. Salty *executes* the style file. The consequences run both ways: Salty can run arbitrary TypeScript at build time — including `await fetch()` — because it's really running your code, while Panda can find styles anywhere in a `.tsx` file because it never has to run anything. Salty's price for that is the filename suffix. **Output model.** Panda emits atomic utilities; Salty emits one content-hashed class per distinct style object. Identical style objects deduplicate to a single rule, and `importStrategy: 'component'` splits the stylesheet per route, but the scaling curve is genuinely different: Panda's stylesheet grows with the number of distinct *declarations*, Salty's with the number of distinct *components*. That's the tradeoff to make a decision about before you start, not after. **No codegen step.** There's no `panda codegen` and no `styled-system/` directory to import from. Types come from your own source files. `saltygen/` is CSS output only — a build artifact you gitignore, never a module surface. **No patterns, no style props.** `hstack`, `vstack`, `grid` and friends have no equivalent; build them as styled components or templates once. And `` has no equivalent either — Salty's `css-*` props are for prop tokens you declared, not for arbitrary CSS properties at the call site. | Panda CSS 1.11 | Salty CSS | | :-- | :-- | | `css({ … })` | `className({ base: { … } })` | | `cva({ base, variants, … })` | `styled(el, { base, variants, … })` | | `styled.div` from `styled-system/jsx` | `styled("div", …)` from `@salty-css/react/styled` | | `` style props | No equivalent — declare a variant or a `{props.x}` token | | `theme.tokens` | `defineVariables` | | `theme.semanticTokens` | `defineVariables` → `conditional` | | `color: "brand.500"` | `color: "{colors.brand.500}"` | | `_hover`, `_focus` | `"&:hover"`, `"&:focus"` | | `_dark` | `conditional.theme` + `data-theme`, or a dark media query | | `defineRecipe` / `defineSlotRecipe` | `styled` variants / `defineTemplates` | | Patterns (`hstack`, `vstack`, …) | No equivalent — compose your own | | `panda.config.ts` | `salty.config.ts` | | `panda codegen` → `styled-system/` | No codegen; `saltygen/` is CSS output | | PostCSS plugin | Vite / Webpack / Next plugin | | `@layer reset, base, tokens, recipes, utilities` | `@layer imports, reset, global, templates, fonts, l0…l8` | ```ts import { cva } from "../styled-system/css"; export const button = cva({ base: { padding: "0.6em 1.2em", borderRadius: "md" }, variants: { tone: { solid: { bg: "brand.500", color: "white" }, ghost: { bg: "transparent", color: "brand.500" }, }, }, defaultVariants: { tone: "solid" }, }); // ``` The conditional string-building disappears, and with it the merge utility whose job was deciding which of two conflicting `bg-` classes wins. `primary` is a typed boolean prop and the conflict is resolved at build time instead. The cost is the one named above: a stylesheet that grows with the number of distinct components rather than the number of distinct declarations. **On running both at once.** You can, and for a migration of this size you probably should. Both put their output in cascade layers, so they sort rather than fight. Be deliberate about the order, though — layers are ordered by first appearance in the document, so whichever stylesheet the browser encounters last has its layers sorted last, and later layers win ties at equal specificity. Which stylesheet you import first is a real decision, not a formatting one. Use `priority` when a specific Salty rule needs to beat a utility. --- ##### Preprocessors and plain CSS ###### Sass 1.102 (and CSS Modules) The most mechanical migration on the page and the lowest-risk one. Most of it is a syntax transformation you can do file by file, and nothing in a Sass codebase depends on a runtime you have to unwind. One thing genuinely changes: scoping. Sass gives you organisation, not isolation — nothing stops you writing `.card .title { … }` and reaching into another component's markup. Salty hashes every component, so cross-component selectors stop being available, and composition happens through components, tokens and templates instead. That's the part that takes rethinking; the rest is typing. Worth naming the upgrade too, because it's easy to read tokens as a lateral move. Sass `$variables` are inlined at compile time and gone from the output. Salty tokens compile to real CSS custom properties, which means they stay live in the cascade — and that's precisely what makes attribute-driven theming possible at all. | Sass 1.102 | Salty CSS | | :-- | :-- | | `.scss` partials | `*.css.ts` files | | `$brand: #0070f3` | `defineVariables` → `{colors.brand}`, a real custom property | | `@mixin` / `@include`, no args | `defineTemplates`, applied with `true` | | `@mixin` with args | A function template, or a plain TS function returning a style object | | `@use` / `@forward` | `import` / `export` | | `&` nesting | `&` nesting, in objects | | `@media (min-width: 768px)` | `defineMediaQuery` → `"@tabletUp"` | | `color.adjust` / `color.scale` | The [`color()`](/react/docs/basics/color-function) helper | | `@each` / `@for` | Plain TypeScript | | `kebab-case` properties | `camelCase` keys | | Global by default | Hashed per component | | CSS Modules `Foo.module.css` | `foo.css.ts` with `styled()` or `className()` | ```scss @use "./tokens" as *; @mixin interactive { cursor: pointer; transition: background 150ms ease; &:focus-visible { outline: 2px solid $focus-ring; outline-offset: 2px; } } .button { @include interactive; padding: 0.6em 1.2em; background: $brand; color: $paper; } ``` ```ts import { defineTemplates } from "@salty-css/core/factories"; export default defineTemplates({ interactive: { base: { cursor: "pointer", transition: "background 150ms ease", "&:focus-visible": { outline: "2px solid {colors.focusRing}", outlineOffset: "2px", }, }, }, }); ``` ```ts import { styled } from "@salty-css/react/styled"; export const Button = styled("button", { base: { interactive: true, padding: "0.6em 1.2em", background: "{colors.brand}", color: "{colors.paper}", }, }); ``` A mixin that takes arguments becomes a function template — same idea, but the parameter is typed, so a bad call is a compile error at the call site rather than Sass quietly emitting something odd. **CSS Modules specifically** is the least eventful version of this. Rename `Foo.module.css` to `foo.css.ts`, rewrite each rule as a `styled()` or `className()` call, update the import. You already had scoping, so nothing about the mental model changes; you're trading a generated class-name object for typed components. --- ##### A sequence that works Roughly the order I'd do it in, for any of the above: 1. **Install alongside.** Plugin, `salty.config.ts`, import `saltygen/index.css` at the root. Delete nothing. 2. **Port tokens first.** Colours, spacing, type scale into `defineVariables`. Everything downstream references them, so this is the file the rest of the migration leans on. 3. **Set `strict: 'warn'`** while you work, so a mistyped token path is a warning rather than a failed build mid-port. Flip it to `true` at the end. 4. **Port leaf components before containers.** A button, a badge, an input. Leaves have the fewest inbound style dependencies and give you the fastest read on whether your token names hold up. 5. **Do globals and the reset deliberately.** It's the one place the old and new stylesheets genuinely compete, and it's easier to reason about once the components are settled. 6. **Remove the old library when its last import is gone** — not before. Every step there ships. That's the point of the ordering. #### Framework agnostic APIs Salty CSS ships wiring for a few setups out of the box — Next.js, Astro, and React on Vite or Webpack. This guide is for the case where yours isn't one of them: a Vue app, a Svelte project, Angular, or a stack nobody has pointed Salty at yet. The short version is that you're probably fine, and the part you lose is smaller than you'd expect. The reason is that almost everything you write in a `.css.ts` file has no idea which framework you picked. Tokens, templates, media queries, fonts, keyframes, global styles, helpers, class names: all of it is TypeScript that runs in Node while your project builds, and its only output is text in a stylesheet. None of it renders anything, so none of it needs to know how your framework renders. Yes, React is listed as a framework next to Next.js and Astro. I'm aware. Plain React on Vite works well enough that it needs a seat at the table, and the menu only has so many slots. The one genuine exception is `styled`, and it's worth getting out of the way first: a component factory has to hand back a real component in your framework's own shape, and there's no universal JSX-shaped function that covers React, Astro, Vue, Svelte and Angular at once. So Salty publishes a `styled` per supported framework, and everywhere else you author with `className` instead. Which makes the actual requirement much narrower than a list of frameworks: **Salty needs Vite or Webpack.** If your build runs on one of those, the answer is yes. This guide is the authoring story — what you write, and what changes when `styled` isn't available. For the support matrix itself, which versions are tested and what's known to work, Compatibility is the page. --- ##### Where the line falls The split isn't really "React things" and "other things" — it's **render time** versus **build time**. `styled` is the only API that produces something your framework has to render. Everything else produces text: a custom property, a keyframes rule, a media query, a class name. Text doesn't care what put it on the page. | What you're doing | API | Import from | | :-- | :-- | :-- | | A class string with the full styling surface | `className` | `@salty-css/core/class-name` | | Design tokens, themes | `defineVariables` | `@salty-css/core/factories` | | Reusable style bundles | `defineTemplates` | `@salty-css/core/factories` | | Document-level styles and resets | `defineGlobalStyles` | `@salty-css/core/factories` | | Named media queries | `defineMediaQuery` | `@salty-css/core/factories` | | Fonts and external CSS | `defineFont`, `defineImport` | `@salty-css/core/factories` | | Project configuration | `defineConfig` | `@salty-css/core/config` | | Build-time color math, fluid sizing | `color`, `defineViewportClamp` | `@salty-css/core/helpers` | | Animations | `keyframes` | `@salty-css/core/css` | | Styles that only exist at request time | `defineRuntime` | `@salty-css/core/runtime` | | **A typed component with variant props** | **`styled`** | **`@salty-css/react/styled`, `@salty-css/astro/styled`** | One note if you've been reading the React docs: those pages import several of these from `@salty-css/react/*` — `@salty-css/react/config` for `defineMediaQuery`, `@salty-css/react/keyframes`, and so on. Those subpaths are straight re-exports of the core ones, unchanged, so either import resolves to the same function. Core is the one to reach for when React isn't in the picture, and it's the honest home for all of them. --- ##### The real requirement: Vite or Webpack Salty's build plugin does two jobs, and both of them are bundler jobs rather than framework jobs. The first runs once when the build starts: find every file matching a Salty suffix, evaluate it, and write the whole project's CSS to `saltygen/index.css`. The second hooks the module loader, so each `.css.ts` file gets rewritten on its way through the bundler — the style objects you authored are replaced by the class names the compiler just produced. In dev, a third piece watches those files and regenerates as you type. Loader hook, watcher, build-start hook. That's a bundler's vocabulary, which is why the supported-framework list is really a list of bundlers wearing different hats: `@salty-css/next` wraps Webpack and Turbopack, `@salty-css/astro` is a Vite plugin plus the Astro integration, and `@salty-css/vite` and `@salty-css/webpack` are the plain versions of the same thing. So the question to ask about your own stack isn't whether your framework is on a list. It's whether your dev server runs on Vite or Webpack — and most of the current generation of meta-frameworks build on Vite, while plenty of long-lived apps still build on Webpack. Astro was supported before it had its own package for exactly this reason: it's Vite underneath, so the Vite plugin already worked. I've also had this running inside an Angular app, which meant writing CSS-in-JS in Angular — that's a sentence you don't hear often, even though Angular is all about type safety. It shipped on TypeScript from day one while the rest of the ecosystem took years to come around — and it's the reason I know TypeScript as well as I do. Shoutout to Angular. ###### Wiring the plugin For Vite: ```ts import { defineConfig } from "vite"; import { saltyPlugin } from "@salty-css/vite"; export default defineConfig({ plugins: [saltyPlugin(__dirname)], }); ``` For Webpack — note that `saltyPlugin` mutates your config object in place rather than returning a new one: ```js const { saltyPlugin } = require("@salty-css/webpack"); const config = { // your existing webpack config }; saltyPlugin(config, __dirname); module.exports = config; ``` `npx salty-css init` can do the Vite edit for you. Webpack is a manual edit today. ###### The rest of the setup Four things, none of them framework-shaped: 1. **Install** the core package and your bundler's plugin: `npm i @salty-css/core @salty-css/vite` (or `@salty-css/webpack`). 2. **Create `salty.config.ts`** in the same folder as your bundler config. 3. **Import the generated stylesheet once** at your app entry, from whatever global CSS file you already load: `@import "../saltygen/index.css";`. 4. **Build once** — run your dev server, or `npx salty-css build` — so `saltygen/` exists before the first render. ```ts import { defineConfig } from "@salty-css/core/config"; export const config = defineConfig({ // variables, templates, modifiers go here as you grow }); ``` From here on, nothing on this page is specific to anything. It's the same API surface the framework docs describe, minus one function. --- ##### Authoring with `className` `className` gives you the entire styling surface — variants, nesting, pseudo-classes, tokens, media queries, templates — and hands back a class string instead of a component. That's the trade: you keep your own markup, and you apply the class yourself. ###### How you define it ```ts import { className } from "@salty-css/core/class-name"; export const buttonClass = className({ base: { display: "inline-flex", alignItems: "center", gap: "0.5em", padding: "0.6em 1.2em", borderRadius: "6px", border: "1px solid transparent", cursor: "pointer", "&:hover": { filter: "brightness(1.1)" }, "&:disabled": { opacity: 0.5, pointerEvents: "none" }, }, variants: { tone: { solid: { background: "{colors.brand.main}", color: "{colors.paper}" }, ghost: { background: "transparent", borderColor: "currentColor" }, }, size: { small: { fontSize: "0.85rem" }, large: { fontSize: "1.15rem" }, }, }, }); ``` ###### How you use it The export is a string. Put it wherever your framework puts class names — a `class` attribute, a binding, a `setAttribute` call, a template literal alongside classes from somewhere else. ```ts import { buttonClass } from "./styles/button.css"; // no variants — just the base class buttonClass; // → "eyjPN" // variants are chained, and each call returns a new instance buttonClass.variant("tone", "solid").variant("size", "large"); // → "eyjPN tone-solid size-large" ``` Two things about that value worth knowing before they surprise you. It's a `String` object rather than a string primitive, so it carries the `.variant()` method around with it. Almost everywhere that's invisible — it concatenates, interpolates and compares as text like anything else. But if something in your stack does a strict `typeof x === "string"` check, coerce it first with a template literal or `String(...)`. And `defaultVariants` is accepted in the options object, but `className` does not apply it for you. `.variant()` is the only thing that appends classes, so a call with no chain gets you the base class and nothing else. When you want defaults, wrap the class in a small function: ```ts export const button = ({ tone = "solid", size = "small", }: { tone?: "solid" | "ghost"; size?: "small" | "large"; } = {}) => buttonClass.variant("tone", tone).variant("size", size); ``` ```ts button(); // → base + tone-solid + size-small button({ tone: "ghost" }); // → base + tone-ghost + size-small ``` That wrapper is also the natural seam for a component in your framework: it already has the prop names, the defaults and the types. What it renders is up to you. --- ##### The rest of the system Everything a design system needs comes out of core, and none of it changes shape here. Define once, reference from anywhere. ```ts import { defineVariables } from "@salty-css/core/factories"; export default defineVariables({ colors: { brand: { main: "#0070f3" }, ink: "#101014", paper: "#fbfbfd", }, conditional: { theme: { light: { bg: "{colors.paper}", text: "{colors.ink}" }, dark: { bg: "{colors.ink}", text: "{colors.paper}" }, }, }, }); ``` ```ts import { defineMediaQuery, defineTemplates } from "@salty-css/core/factories"; import { keyframes } from "@salty-css/core/css"; import { defineViewportClamp } from "@salty-css/core/helpers"; export const tabletDown = defineMediaQuery((media) => media.maxWidth(900)); export const fhdClamp = defineViewportClamp({ screenSize: 1920, minMultiplier: 0.6, maxMultiplier: 1.2, }); export const fadeIn = keyframes({ animationName: "fadeIn", params: { duration: "200ms", easing: "ease-out" }, from: { opacity: 0 }, to: { opacity: 1 }, }); export default defineTemplates({ textStyle: { body: { fontSize: "1rem", lineHeight: 1.5 }, heading: { fontSize: fhdClamp(48), fontWeight: 700, lineHeight: 1.1 }, }, }); ``` Then consume all of it from a class, exactly as a `styled` component would: ```ts import { className } from "@salty-css/core/class-name"; import { fadeIn } from "./system.css"; export const panel = className({ base: { textStyle: "body", background: "{theme.bg}", color: "{theme.text}", padding: fhdClamp(32), animation: fadeIn, "@tabletDown": { padding: "1rem" }, }, }); ``` Theming deserves a specific mention, because it's the part people assume must need a provider. It doesn't — anywhere. A conditional token group compiles to `[data-theme="dark"] { --theme-bg: … }` in the static stylesheet, so switching themes means setting one attribute on an ancestor element and letting the browser's own cascade repaint. No context, no re-render, no library code in the loop. Whatever sets that attribute in your framework is the entire integration. --- ##### What you give up without `styled` Worth being straight about the size of the gap, because it's smaller than it sounds and it's all in one place. `styled` gives you a typed component whose variants are JSX props, consumed before they reach the DOM; `element` and `as` for swapping the rendered tag; `defaultProps` and `passProps` for the HTML attribute plumbing; and the ability to extend an existing Salty component, which also bumps the extension into the next cascade layer so its rules win without a specificity fight. Every item on that list is component ergonomics. None of it is CSS. The stylesheet you get from `className` is the same stylesheet — same hashing, same layers, same tokens, same output file. What you're missing is the wrapper that maps props to variants, and that's the small function from the section above plus however your framework declares a component. If you want to go further than that, core does export the generator classes the framework packages are built on — that's how `@salty-css/react/styled` and `@salty-css/astro/styled` are put together. It's unsupported territory and the shape can move between releases, but the door isn't locked. --- ### Reference #### `styled` `styled` creates a typed component from an HTML tag or from another component. You hand it a style object; you get back a component where every variant name you declared is a typed prop — consumed for styling, and kept off the DOM unless you opt it back in. The call has to live in a file the compiler reads (`.css.ts`, `.css.tsx`, `.salty.ts`, `.styled.ts`, `.styles.ts`) and has to be a top-level `export`. In a plain `.ts` file it type-checks fine and emits no CSS. For how these components are meant to be composed and extended in a project, see [Styled components](/react/docs/basics/styled-components) in Basics. ##### Import ```ts import { styled } from "@salty-css/react/styled"; ``` Astro uses `@salty-css/astro/styled`. Next.js uses the React subpath — only the build plugin is Next-specific. ##### Signature ```ts styled(tag: string | ComponentType, params: StyledParams): StyledComponent ``` **`tag`** — an HTML tag name (`"div"`, `"button"`, `"a"`, …) or a component. A component is *wrapped*, not replaced; see [Extending a component](#extending-a-component). Third-party components have one requirement: they must accept a `className` prop, since that's the only channel Salty has to deliver the generated styles. **`params`** — the options object below. Every key is optional. **Returns** — a component that accepts the variant props you declared, the native props of the underlying element, and `className`, `style`, `as`, `children`, `ref`, plus any [`css-*` prop tokens](#prop-tokens) your styles reference. ##### Options | Key | What it does | | :-- | :-- | | [`base`](#base) | The styles every instance gets. | | [`variants`](#variants) | Named style branches, each exposed as a typed prop. | | [`compoundVariants`](#compound-variants) | Extra styles for when several variant values are active together. | | [`anyOfVariants`](#any-of-variants) | Extra styles shared by several variant values. Never wins a conflict. | | [`defaultVariants`](#default-variants) | Which branch applies when the consumer omits the prop. | | [`defaultProps`](#default-props) | HTML attributes the element renders with by default. | | [`element`](#element) | Render a different tag without redefining the styles. | | [`passProps`](#pass-props) | Let variant props through to the element instead of consuming them. | | [`className`](#class-name) | Add your own class name alongside the generated hash. | | [`displayName`](#display-name) | The name this component goes by in build output and DevTools. | | [`priority`](#priority) | Which cascade layer the rules land in. Higher wins ties. | ###### `base` Styles applied to every instance, in Salty's full style-object syntax: ```ts export const Card = styled("div", { base: { padding: "1.5rem", borderRadius: "12px", background: "{theme.background}", "&:hover": { boxShadow: "0 8px 24px rgb(0 0 0 / 0.08)" }, "& > svg": { flexShrink: 0 }, "@tabletDown": { padding: "1rem" }, }, }); ``` What's accepted inside the object: - **Nested selectors** via `&` — `"&:hover"`, `"&:not(:hover)"`, `"& > svg"`, `"& + &"`, grouped `"&:hover, &:focus"`. - **Token references** — `{path.to.token}`, themed ones as `{theme.xxx}`. Paths are validated at build time. - **At-rules** — an inline `"@media (...)"`/`"@container (...)"` key, or a name you registered with `defineMediaQuery` as `"@tabletDown"`. An unknown `@name` is emitted as a literal at-rule and silently never matches. - **Templates and modifiers** — applied as keys and values inside the object. - **Values** — `string`, `number`, a function, or a promise. Functions and promises are resolved by the compiler, so the result lands in the stylesheet as a literal. Bare numbers get the unit from `defineConfig({ defaultUnit })`, `px` by default. ###### `variants` Each top-level key is an axis and becomes a typed prop; each child key is one value on that axis. ```ts export const Button = styled("button", { base: { padding: "0.6em 1.2em", cursor: "pointer" }, variants: { variant: { solid: { background: "{theme.color}", color: "{theme.background}" }, outlined: { border: "1px solid currentColor" }, }, size: { small: { fontSize: "0.8em" }, large: { fontSize: "1.2em" }, }, loading: { true: { opacity: 0.6, pointerEvents: "none" }, }, }, }); ``` ```tsx ; ``` Note the import path: `./components/button.css`, without the `.ts`. The full picture of which suffix to use when, and where these files tend to live as a project grows, is in [File structure](/react/docs/getting-started/file-structure). ###### The `-r` pair `-r` splits the work across two files instead of one — the styled definition, and a React component that renders it: ```bash npx salty-css generate components/card -t section -r ``` ```ts import { styled } from "@salty-css/react/styled"; export const CardWrapper = styled("section", { base: { // Add your styles here }, }); ``` ```tsx import { CardWrapper } from "./card.css"; interface CardComponentProps { text?: string; } export const CardComponent = ({ text = "Lorem ipsum" }: CardComponentProps) => { return {text}; }; export default CardComponent; ``` The naming is the part to notice: the styled export becomes `Wrapper` and the component `Component`, because the two now live in the same folder and can't share a name. On Astro the wrapper is a `.astro` file instead. Reach for this when a component needs real logic around its markup — props, state, a bit of composition — and keep the single-file form when it doesn't. Unlike the other commands, `generate` doesn't need a `package.json`, so it also works in a bare package inside a monorepo. ##### `build` ```bash npx salty-css build [directory] ``` Compiles every Salty file it can reach and regenerates `saltygen/` from scratch. | Argument / option | What it does | | :-- | :-- | | `[directory]` | Project directory. Falls back to `defaultProject` in `.saltyrc.json`. | | `-d, --dir ` | The same as the argument. | | `--watch` | Stay open and rebuild on change. | | `--mode ` | `production` or `development`. Defaults to detection from `NODE_ENV`. Any other value is an error. | With a bundler plugin wired up, your dev server already does this on save and you'll rarely type it. It earns its place in four places: the `prepare` script, a CI step, debugging a build you want to run in isolation, and any setup where the plugin isn't running at all. ```bash npx salty-css build --watch # rebuild on change, no dev server npx salty-css build --mode production # what actually ships ``` `--mode` is worth knowing about because development and production builds differ in one visible way: dev builds render `data-component-name` on every styled element, production builds strip it. If you're about to write a selector against production HTML, this is the build to check it against — [Testing](/react/docs/basics/testing) goes further into that. `--watch` watches the project directory recursively and splits changes two ways. A change to a component file recompiles that one file; a change to `salty.config.ts`, or to any Salty file containing a `defineX(` or `keyframes(` call, triggers a full rebuild — those define things everything else references, so they can't be recompiled in isolation. The test is a plain text match on the file's contents, which means a `defineVariables(` sitting in a comment costs you a full rebuild for nothing. It's the same split the bundler plugins use, with the same caveat: the incremental path appends and patches, it never prunes. Stale rules after a rename or a delete mean "rebuild", not "the compiler is wrong." `saltygen/` is a build artifact whichever way it gets built — don't commit it, don't hand-edit it, and don't write a test against its internals. [File structure](/react/docs/getting-started/file-structure) covers what ends up in there. ##### `update` ```bash npx salty-css update [version] npx salty-css up [version] ``` Bumps every `@salty-css/*` package in your `package.json` together, then offers to rebuild. | Argument / option | What it does | | :-- | :-- | | `[version]` | The version to move to. Defaults to `latest`. | | `-v, --version ` | The same as the argument. | | `-y, --yes` | Skip both prompts — the install and the rebuild. | | `-d, --dir ` | Directory to rebuild afterwards. Falls back to `defaultProject`. | | `--legacy-peer-deps` | Passed straight through to npm. Not recommended — it quiets a version conflict rather than resolving one. | ```bash npx salty-css up # everything to latest npx salty-css up 0.4.2 # or pin them all to one version ``` *Together* is the important word. `@salty-css/core`, `@salty-css/react` and your bundler plugin are built and released as a set, and mixing versions across them produces confusing failures rather than clear ones — a component that renders with no styles, a token path that type-checks and compiles to nothing. Bumping one by hand is the shortest route to an afternoon you hadn't planned on. What it actually does: reads your dependencies *and* devDependencies for anything named `salty-css` or `@salty-css/*`, installs them all at the target version with npm, prints what each one ended up at, then asks whether to rebuild — because `saltygen/` was generated by the old compiler and wants regenerating by the new one. Starting your dev server does that too. Two ways it stops early, both harmless: no Salty packages in the `package.json` it can see means you're in the wrong directory, and it says so rather than installing anything. No `--dir` and no `defaultProject` means it skips the rebuild with a warning and leaves you to run `build` yourself. Salty is pre-1.0, so minor APIs can still move between releases. Pin your versions rather than floating on a caret, read the [release notes](https://github.com/margarita-form/salty-css/releases) before you bump, and you'll be fine. [Updates](/react/docs/guides/updates) is the guide version of this command. ##### `--version` ```bash npx salty-css --version ``` Prints the version of the CLI that's running, then every Salty package in your `package.json` with the range you have declared: ```bash info: CLI is running: 0.4.2 info: @salty-css/core: ^0.4.2 info: @salty-css/react: ^0.4.2 ``` `-v` is the short form, and running `npx salty-css` with no command at all prints the same thing. This is the output to paste into a bug report — mismatched versions explain enough failures that it's the first thing worth ruling out. ##### Running it in CI Three things behave differently without an interactive terminal, and all three have a flag: - **`init` fails** rather than installing without asking. `--yes` accepts the package list up front; `--skip-install` skips the install entirely. - **`update` skips the rebuild** silently and installs anyway. `--yes` takes both prompts. - **`prepare` doesn't always run.** Some platforms install with `--ignore-scripts`, which skips it — add `npx salty-css build` to the build step explicitly there. It's also the honest way to run the compiler in isolation when you're debugging one.