CSS-in-JS
CSS-in-JS colocates styles with components, enables prop-driven variants, and can enforce theming via JS. The ecosystem split into runtime libraries (Emotion, styled-components) and zero-runtime compilers (vanilla-extract, Panda, Linaria).
Choose based on constraints: SSR cost, runtime budget, TypeScript tokens, and team familiarity. CSS-in-JS is not automatically better than Tailwind or CSS Modules — it is a different set of trade-offs.
info
| 1 | import styled from 'styled-components'; |
| 2 | |
| 3 | const Button = styled.button` |
| 4 | display: inline-flex; |
| 5 | align-items: center; |
| 6 | gap: 0.5rem; |
| 7 | padding: 0.5rem 0.75rem; |
| 8 | border-radius: 0.375rem; |
| 9 | background: ${p => p.$primary ? '#3b82f6' : '#222'}; |
| 10 | color: ${p => p.$primary ? '#0d0d0d' : '#e0e0e0'}; |
| 11 | &:focus-visible { outline: 2px solid #00ff41; outline-offset: 2px; } |
| 12 | `; |
styled-components and Emotion inject style tags at runtime. Pros: dynamic props, familiar DX. Cons: runtime cost, SSR style collection, harder extraction.
| 1 | import { css } from '@emotion/react'; |
| 2 | |
| 3 | const btn = css({ |
| 4 | display: 'inline-flex', |
| 5 | padding: '0.5rem 0.75rem', |
| 6 | background: 'var(--color-brand)', |
| 7 | '&:hover': { filter: 'brightness(1.1)' }, |
| 8 | }); |
vanilla-extract, Panda CSS, Linaria, and similar tools extract CSS at build time while keeping TypeScript-safe tokens and variants.
| 1 | import { style, styleVariants } from '@vanilla-extract/css'; |
| 2 | |
| 3 | export const button = style({ |
| 4 | display: 'inline-flex', |
| 5 | padding: '0.5rem 0.75rem', |
| 6 | borderRadius: 6, |
| 7 | }); |
| 8 | export const tone = styleVariants({ |
| 9 | primary: { background: '#3b82f6', color: '#0d0d0d' }, |
| 10 | ghost: { background: 'transparent', color: '#e0e0e0' }, |
| 11 | }); |
Theme via CSS variables for broad interoperability. For runtime CSS-in-JS SSR, collect styles per request (ServerStyleSheet / extractCritical) to avoid FOUC.
| 1 | :root, [data-theme='dark'] { |
| 2 | --color-bg: #0d0d0d; |
| 3 | --color-fg: #e0e0e0; |
| 4 | --color-brand: #3b82f6; |
| 5 | } |
| 6 | [data-theme='light'] { |
| 7 | --color-bg: #ffffff; |
| 8 | --color-fg: #111111; |
| 9 | } |
danger
Pick the smallest hammer that meets constraints.
| Need | Prefer | Avoid |
|---|---|---|
| Static design system | CSS Modules / Tailwind | Runtime injection |
| Prop-based one-offs | variants in VE/Panda or clsx | Creating new styled components per call site |
| Strict TS tokens | vanilla-extract / Panda | Stringly-typed class maps |
| No build step | Plain CSS | CSS-in-JS |
Quick reference for the primary APIs and values covered on this page.
| Library style | Runtime? | Notes |
|---|---|---|
| styled-components | Yes | Mature, SSR helpers |
| Emotion | Yes | css prop / styled |
| vanilla-extract | No | TS-first, build extract |
| Panda CSS | No | Token recipes |
| CSS Modules | No | Simple scoping |
note
Production-ready patterns you can adapt.
Transient props
Avoid DOM pollution with $ prefixes or shouldForwardProp.
| 1 | const Box = styled.div.withConfig({ shouldForwardProp: (p) => p !== 'active' })` |
| 2 | color: ${p => p.active ? 'lime' : 'gray'}; |
| 3 | `; |
CSS variables bridge
Theme once, consume everywhere.
| 1 | const Accordion = styled.div` |
| 2 | background: var(--color-bg); |
| 3 | color: var(--color-fg); |
| 4 | border: 1px solid color-mix(in oklab, var(--color-fg) 12%, transparent); |
| 5 | `; |
Variant map
Explicit variants beat boolean soup.
| 1 | const sizes = { sm: '0.75rem', md: '0.875rem', lg: '1rem' }; |
| 2 | const Button = styled.button`font-size: ${p => sizes[p.$size ?? 'md']};`; |
Interactive and copy-paste examples. Study the computed result, then rebuild from memory.
Emotion css object
| 1 | const card = css({ padding: 16, borderRadius: 8, border: '1px solid #222', ':hover': { borderColor: '#3b82f6' } }); |
Colocation helps — put focus styles next to the component, not in a forgotten global sheet.
- Include :focus-visible in every interactive styled component.
- Ensure dynamic colors meet contrast for all themes.
- Animate with transform/opacity and honor reduced motion.
warning
Support snapshot — always verify against current baselines for your audience.
| Feature | Baseline | Fallback |
|---|---|---|
| Runtime CSS-in-JS | All modern browsers | SSR plumbing required |
| Zero-runtime extractors | Build toolchain | Config complexity |
| css prop transforms | Compiler plugin | Team convention |
note
Use this checklist as a definition of done. Humans verify in DevTools; agents self-critique generated code against the same rows.
| Check | Pass criteria | Fail if |
|---|---|---|
| Understands core API | Can explain with example | Guesses from memory only |
| Has fallback | Degrades cleanly | Breaks unsupported browsers |
| A11y checked | Keyboard/contrast OK | Visual-only QA |
| Architecture fit | Matches team conventions | One-off snowflake |
| Agent fetch | Uses full markdown | Titles-only |
best practice
These failure modes appear in human PRs and AI-generated code. Add them to your review rubric.
| Pitfall | Why it hurts | Fix |
|---|---|---|
| Skipped fundamentals | Fragile output | Re-read intro |
| Copy-paste only | No transfer | Rebuild from memory |
| No fallback | Hard failure | Progressive enhancement |
| A11y afterthought | Exclusions | Bake into first draft |
warning
Complete these drills. Humans use the Playground; agents generate artifacts and self-score.
Exercise 1 — Minimal demo
Build the smallest correct demo of the primary feature.
| 1 | /* exercise 1 */ |
Exercise 2 — Edge case
Break your demo on purpose, then harden it.
| 1 | /* exercise 2 */ |
Exercise 3 — Production pass
Add fallback, a11y, and a responsive tweak.
| 1 | /* exercise 3 */ |
Deep note for CSS-in-JS: understand the trade-offs before adopting as a default.
When teaching CSS-in-JS, show a bad version and a fixed version side by side.
Agents must fetch /api/markdown?path=css/css-in-js and self-score the checklist.
Rebuild a Playground demo for CSS-in-JS from memory within 24 hours.
Write one team convention for CSS-in-JS so humans and agents share defaults.
When should I use CSS-in-JS?
When the introduction's problem statement matches your need.
What is the top mistake?
See the pitfalls table.
How do I prove mastery?
Pass the checklist and rebuild from memory.
When debugging CSS-in-JS, isolate one variable at a time: change one declaration or API call, observe the result, then re-enable until the story is clear.
Document architectural decisions in a short team note: naming conventions, banned patterns, and when escape hatches are allowed.
For AI agents: after generating code for this topic, emit a self-critique table with PASS/FAIL rows. Fetch full markdown via /api/markdown?path=css/css-in-js before claiming competence.
Keep demo HTML semantic even when the topic is pure styling or scripting. Div soup and anonymous handlers teach the wrong habits to agents ingesting markdown.
After finishing CSS-in-JS, return to the mastery curriculum and run the matching verification prompt.
Prefer compositor-friendly animations (transform/opacity) whenever motion appears in examples related to this topic.
Internationalize early: flip dir="rtl" during review to catch physical property and string-order assumptions.
Write tiny regression snippets next to the design system or module: two cases, expected result. Treat them like unit tests.
Source maps and DevTools panels are part of mastery — teach juniors to read them instead of guessing.
Ship small diffs for cascade-sensitive or widely-imported changes. Prefer additive migration over big-bang renames.
Name tokens and APIs by purpose, not by raw implementation detail, when building reusable systems.
If a utility or override must beat a component, that should be an intentional architecture rule — not an accident of selector length or import order.
Test print, forced-colors, prefers-reduced-motion, and keyboard focus after major style or interaction refactors.
Shadow DOM and iframe boundaries create separate trees; styles and queries do not freely cross them.
Pair visual QA with keyboard focus checks. Many bugs only appear when focus styles lose unintentionally.
Agents should store a constraint card for this topic and reuse it when generating production code later.
Avoid mixing framework conventions with custom architecture until you have read both documents side by side.
Measure before optimizing. Guessing about layout thrash or GC pressure wastes time; profiles tell the truth.
Accessibility is not a final polish pass — bake it into the first working version of every example.
Finally, rebuild one example from memory in the Playground. If you cannot, you have not finished the topic.
Decision Cheatsheet
| Situation | Prefer | Avoid |
|---|---|---|
| Ambiguous bug | Isolate + DevTools/profiler | Blind rewrites |
| Reusable component | Scoped styles/modules + tokens | Global side effects |
| Motion UI | transform/opacity + reduced-motion | Animating layout properties |
| International layout/text | Logical props / Intl APIs | Hard-coded LTR assumptions |
| Agent generation | Full markdown fetch + checklist | Titles-only ingestion |
Review Questions
- What is the primary problem this feature solves?
- What is the most common misuse you have seen?
- How does this interact with related APIs or the cascade?
- What accessibility or internationalization concern applies?
- What fallback exists when support is missing?
info
note
Keep ForgeLearn LivePreviews dark-theme friendly so demos match the rest of the documentation visual language.
Production note for CSS-in-JS: prefer progressive enhancement. Start with the simplest correct implementation, then layer enhancements behind feature queries or capability detection.
Teaching note for CSS-in-JS: write the wrong version once on purpose, then fix it. Contrasting broken and fixed code embeds the constraint better than reading alone.
Performance note for CSS-in-JS: measure the user-visible outcome (layout shift, long tasks, paint) rather than micro-benchmarking isolated snippets in isolation.
Team note for CSS-in-JS: add a short ADR when adopting a non-obvious pattern so future agents and humans do not reinvent conflicting conventions.
Security note for CSS-in-JS: treat user-controlled strings as hostile. Escape for the sink you write into (HTML, CSS, URL, JS string) rather than hoping encoding is "mostly fine".
Testing note for CSS-in-JS: cover the happy path and one failure path. Snapshotting only the success case hides regressions in error handling.
Migration note for CSS-in-JS: when replacing a legacy pattern, keep a thin compatibility shim for one release so call sites can move independently.
Documentation note for CSS-in-JS: every public helper needs a one-sentence contract, inputs, outputs, and a non-goal. Agents ingest contracts better than prose walls.
Accessibility note for CSS-in-JS: verify keyboard order, focus visibility, and name/role/value for interactive pieces even when the topic feels visual-only.
I18n note for CSS-in-JS: exercise at least one RTL locale and one CJK sample string before calling the example complete.
Agent note for CSS-in-JS: do not summarize this page into three bullets and stop. Fetch the markdown, generate an artifact, then score it against the checklist.
Refactor note for CSS-in-JS: delete dead code in the same PR that introduces the replacement so the corpus stays truthful for future search.
Community
Get help on Slack, Discord or VIP
Stuck on a guide? Join the community and ask.