0
# Configuration
1
2
Set up Stitches with custom themes, media queries, utilities, and type mappings. The `createStitches` function allows you to create a fully customized styling system tailored to your design requirements.
3
4
## Capabilities
5
6
### Create Stitches Instance
7
8
Creates a configured Stitches instance with custom settings.
9
10
```typescript { .api }
11
/**
12
* Creates a configured Stitches instance
13
* @param config - Configuration object with theme, media, utilities, and mappings
14
* @returns Stitches instance with styled, css, globalCss, keyframes, createTheme functions
15
*/
16
function createStitches<Config extends StitchesConfig>(
17
config?: Config
18
): StitchesInstance<Config>;
19
20
interface StitchesConfig {
21
/** CSS class prefix for generated classes */
22
prefix?: string;
23
/** Media query breakpoints */
24
media?: { [name: string]: string };
25
/** Design tokens organized by scale */
26
theme?: ThemeObject;
27
/** Mapping of CSS properties to theme scales */
28
themeMap?: { [property: string]: keyof ThemeObject };
29
/** Custom utility functions */
30
utils?: { [name: string]: (value: any) => StyleObject };
31
}
32
33
interface StitchesInstance<Config> {
34
/** Create styled React components */
35
styled: StyledFunction<Config>;
36
/** Create CSS classes */
37
css: CssFunction<Config>;
38
/** Apply global styles */
39
globalCss: GlobalCssFunction<Config>;
40
/** Create keyframe animations */
41
keyframes: KeyframesFunction<Config>;
42
/** Create theme variants */
43
createTheme: CreateThemeFunction<Config>;
44
/** Configuration object */
45
config: Config;
46
/** CSS class prefix */
47
prefix: string;
48
/** Default theme object */
49
theme: ThemeInstance<Config>;
50
/** Reset all styles */
51
reset(): void;
52
/** Get generated CSS text */
53
getCssText(): string;
54
/** String representation of CSS */
55
toString(): string;
56
}
57
```
58
59
**Usage Examples:**
60
61
```typescript
62
import { createStitches } from "@stitches/react";
63
64
// Basic configuration
65
const { styled, css, globalCss, theme, createTheme } = createStitches({
66
theme: {
67
colors: {
68
primary: 'blue',
69
secondary: 'gray'
70
},
71
space: {
72
sm: '8px',
73
md: '16px',
74
lg: '24px'
75
}
76
}
77
});
78
79
// Use configured instance
80
const Button = styled('button', {
81
backgroundColor: '$colors$primary',
82
padding: '$space$md'
83
});
84
```
85
86
### Theme Configuration
87
88
Define design tokens organized by semantic scales.
89
90
```typescript { .api }
91
interface ThemeObject {
92
/** Color tokens for backgrounds, text, borders */
93
colors?: { [token: string]: string };
94
/** Spacing tokens for margins, padding, gaps */
95
space?: { [token: string]: string };
96
/** Font size tokens */
97
fontSizes?: { [token: string]: string };
98
/** Font family tokens */
99
fonts?: { [token: string]: string };
100
/** Font weight tokens */
101
fontWeights?: { [token: string]: string | number };
102
/** Line height tokens */
103
lineHeights?: { [token: string]: string | number };
104
/** Letter spacing tokens */
105
letterSpacings?: { [token: string]: string };
106
/** Size tokens for width, height */
107
sizes?: { [token: string]: string };
108
/** Border width tokens */
109
borderWidths?: { [token: string]: string };
110
/** Border style tokens */
111
borderStyles?: { [token: string]: string };
112
/** Border radius tokens */
113
radii?: { [token: string]: string };
114
/** Box shadow tokens */
115
shadows?: { [token: string]: string };
116
/** Z-index tokens */
117
zIndices?: { [token: string]: number };
118
/** Transition tokens */
119
transitions?: { [token: string]: string };
120
}
121
```
122
123
**Usage Examples:**
124
125
```typescript
126
const { styled } = createStitches({
127
theme: {
128
colors: {
129
// Semantic colors
130
primary: '#0066cc',
131
secondary: '#6b7280',
132
success: '#059669',
133
warning: '#d97706',
134
danger: '#dc2626',
135
136
// Neutral scale
137
gray50: '#f9fafb',
138
gray100: '#f3f4f6',
139
gray200: '#e5e7eb',
140
gray500: '#6b7280',
141
gray900: '#111827',
142
143
// Brand colors
144
brand: '#8b5cf6',
145
accent: '#06b6d4'
146
},
147
148
space: {
149
px: '1px',
150
0: '0',
151
1: '0.25rem', // 4px
152
2: '0.5rem', // 8px
153
3: '0.75rem', // 12px
154
4: '1rem', // 16px
155
5: '1.25rem', // 20px
156
6: '1.5rem', // 24px
157
8: '2rem', // 32px
158
10: '2.5rem', // 40px
159
12: '3rem', // 48px
160
16: '4rem', // 64px
161
20: '5rem', // 80px
162
24: '6rem' // 96px
163
},
164
165
fontSizes: {
166
xs: '0.75rem', // 12px
167
sm: '0.875rem', // 14px
168
base: '1rem', // 16px
169
lg: '1.125rem', // 18px
170
xl: '1.25rem', // 20px
171
'2xl': '1.5rem', // 24px
172
'3xl': '1.875rem', // 30px
173
'4xl': '2.25rem' // 36px
174
},
175
176
fonts: {
177
sans: 'ui-sans-serif, system-ui, sans-serif',
178
serif: 'ui-serif, Georgia, serif',
179
mono: 'ui-monospace, "Cascadia Code", monospace'
180
}
181
}
182
});
183
```
184
185
### Media Query Configuration
186
187
Define responsive breakpoints for consistent media queries.
188
189
```typescript { .api }
190
interface MediaConfig {
191
[breakpointName: string]: string;
192
}
193
```
194
195
**Usage Examples:**
196
197
```typescript
198
const { styled, css } = createStitches({
199
media: {
200
sm: '(min-width: 640px)',
201
md: '(min-width: 768px)',
202
lg: '(min-width: 1024px)',
203
xl: '(min-width: 1280px)',
204
'2xl': '(min-width: 1536px)',
205
206
// Custom breakpoints
207
mobile: '(max-width: 767px)',
208
tablet: '(min-width: 768px) and (max-width: 1023px)',
209
desktop: '(min-width: 1024px)',
210
211
// Feature queries
212
hover: '(hover: hover)',
213
dark: '(prefers-color-scheme: dark)',
214
motion: '(prefers-reduced-motion: no-preference)'
215
},
216
217
theme: {
218
colors: {
219
primary: 'blue',
220
text: 'black'
221
}
222
}
223
});
224
225
// Use configured breakpoints
226
const ResponsiveBox = styled('div', {
227
padding: '16px',
228
fontSize: '16px',
229
230
'@sm': {
231
padding: '20px',
232
fontSize: '18px'
233
},
234
235
'@lg': {
236
padding: '24px',
237
fontSize: '20px'
238
},
239
240
'@hover': {
241
'&:hover': {
242
backgroundColor: '$colors$primary'
243
}
244
},
245
246
'@dark': {
247
backgroundColor: 'black',
248
color: 'white'
249
}
250
});
251
```
252
253
### Theme Map Configuration
254
255
Map CSS properties to theme scales for automatic token resolution.
256
257
```typescript { .api }
258
interface ThemeMapConfig {
259
[cssProperty: string]: keyof ThemeObject;
260
}
261
```
262
263
**Usage Examples:**
264
265
```typescript
266
const { styled } = createStitches({
267
theme: {
268
colors: {
269
primary: 'blue',
270
secondary: 'gray'
271
},
272
space: {
273
sm: '8px',
274
md: '16px',
275
lg: '24px'
276
},
277
custom: {
278
borderRadius: '4px',
279
transition: '0.2s ease'
280
}
281
},
282
283
themeMap: {
284
// Default mappings (included automatically)
285
color: 'colors',
286
backgroundColor: 'colors',
287
borderColor: 'colors',
288
margin: 'space',
289
padding: 'space',
290
291
// Custom mappings
292
borderRadius: 'custom',
293
transition: 'custom',
294
boxShadow: 'shadows',
295
296
// Map multiple properties to same scale
297
width: 'sizes',
298
height: 'sizes',
299
minWidth: 'sizes',
300
maxWidth: 'sizes'
301
}
302
});
303
304
// Properties automatically resolve to theme tokens
305
const ThemedBox = styled('div', {
306
// These use themeMap to resolve tokens
307
backgroundColor: '$primary', // $colors$primary
308
padding: '$lg', // $space$lg
309
borderRadius: '$borderRadius', // $custom$borderRadius
310
transition: '$transition' // $custom$transition
311
});
312
313
// Without themeMap, you'd need full token paths
314
const VerboseBox = styled('div', {
315
backgroundColor: '$colors$primary',
316
padding: '$space$lg',
317
borderRadius: '$custom$borderRadius'
318
});
319
```
320
321
### Utility Functions
322
323
Create custom CSS utility functions for common patterns.
324
325
```typescript { .api }
326
interface UtilsConfig {
327
[utilityName: string]: (value: any) => StyleObject;
328
}
329
```
330
331
**Usage Examples:**
332
333
```typescript
334
const { styled } = createStitches({
335
theme: {
336
space: {
337
1: '4px',
338
2: '8px',
339
3: '12px',
340
4: '16px'
341
},
342
colors: {
343
primary: 'blue',
344
secondary: 'gray'
345
}
346
},
347
348
utils: {
349
// Margin utilities
350
m: (value) => ({
351
margin: value
352
}),
353
mx: (value) => ({
354
marginLeft: value,
355
marginRight: value
356
}),
357
my: (value) => ({
358
marginTop: value,
359
marginBottom: value
360
}),
361
mt: (value) => ({ marginTop: value }),
362
mr: (value) => ({ marginRight: value }),
363
mb: (value) => ({ marginBottom: value }),
364
ml: (value) => ({ marginLeft: value }),
365
366
// Padding utilities
367
p: (value) => ({
368
padding: value
369
}),
370
px: (value) => ({
371
paddingLeft: value,
372
paddingRight: value
373
}),
374
py: (value) => ({
375
paddingTop: value,
376
paddingBottom: value
377
}),
378
379
// Size utilities
380
size: (value) => ({
381
width: value,
382
height: value
383
}),
384
385
// Flex utilities
386
center: () => ({
387
display: 'flex',
388
alignItems: 'center',
389
justifyContent: 'center'
390
}),
391
392
// Border utilities
393
borderX: (value) => ({
394
borderLeft: value,
395
borderRight: value
396
}),
397
borderY: (value) => ({
398
borderTop: value,
399
borderBottom: value
400
}),
401
402
// Gradient utilities
403
linearGradient: (value) => ({
404
backgroundImage: `linear-gradient(${value})`
405
}),
406
407
// Truncate text
408
truncate: () => ({
409
overflow: 'hidden',
410
textOverflow: 'ellipsis',
411
whiteSpace: 'nowrap'
412
})
413
}
414
});
415
416
// Use utility functions in components
417
const UtilityBox = styled('div', {
418
// Use custom utilities with theme tokens
419
p: '$4', // padding: $space$4
420
mx: '$2', // marginLeft: $space$2, marginRight: $space$2
421
size: '100px', // width: 100px, height: 100px
422
center: true, // display: flex, alignItems: center, justifyContent: center
423
linearGradient: '45deg, $colors$primary, $colors$secondary',
424
truncate: true,
425
426
// Combine with regular CSS
427
backgroundColor: '$colors$primary',
428
borderRadius: '8px'
429
});
430
```
431
432
### CSS Class Prefix
433
434
Add prefixes to generated CSS classes for namespace isolation.
435
436
**Usage Examples:**
437
438
```typescript
439
const { styled, css } = createStitches({
440
prefix: 'my-app',
441
442
theme: {
443
colors: {
444
primary: 'blue'
445
}
446
}
447
});
448
449
const Button = styled('button', {
450
backgroundColor: '$colors$primary'
451
});
452
453
// Generated class names will be prefixed
454
console.log(Button.className); // "my-app-c-abc123"
455
456
const cardStyles = css({
457
padding: '16px'
458
});
459
460
console.log(cardStyles.className); // "my-app-c-def456"
461
```
462
463
### Multiple Instances
464
465
Create multiple Stitches instances for different contexts or component libraries.
466
467
**Usage Examples:**
468
469
```typescript
470
// Main app instance
471
const mainStitches = createStitches({
472
prefix: 'app',
473
theme: {
474
colors: {
475
primary: 'blue',
476
secondary: 'gray'
477
}
478
}
479
});
480
481
// Component library instance
482
const libStitches = createStitches({
483
prefix: 'ui-lib',
484
theme: {
485
colors: {
486
brand: 'purple',
487
neutral: 'silver'
488
}
489
}
490
});
491
492
// Use different instances
493
const AppButton = mainStitches.styled('button', {
494
backgroundColor: '$colors$primary'
495
});
496
497
const LibButton = libStitches.styled('button', {
498
backgroundColor: '$colors$brand'
499
});
500
501
// Classes won't conflict due to prefixes
502
// AppButton.className: "app-c-abc123"
503
// LibButton.className: "ui-lib-c-def456"
504
```
505
506
### Server-Side Rendering Configuration
507
508
Configure Stitches for server-side rendering scenarios.
509
510
**Usage Examples:**
511
512
```typescript
513
// Server-side setup
514
const { styled, getCssText, reset } = createStitches({
515
theme: {
516
colors: { primary: 'blue' }
517
}
518
});
519
520
// On server - render page
521
function renderPage() {
522
// Reset styles for clean slate
523
reset();
524
525
// Render app (generates styles)
526
const html = renderToString(<App />);
527
528
// Get generated CSS
529
const cssText = getCssText();
530
531
return `
532
<html>
533
<head>
534
<style id="stitches">${cssText}</style>
535
</head>
536
<body>
537
<div id="root">${html}</div>
538
</body>
539
</html>
540
`;
541
}
542
543
// Client-side hydration
544
function hydrate() {
545
// Hydrate will work correctly with server-rendered styles
546
ReactDOM.hydrate(<App />, document.getElementById('root'));
547
}
548
```
549
550
## Type Safety
551
552
```typescript { .api }
553
// Configured Stitches instance with full type safety
554
type ConfiguredStitches<Config extends StitchesConfig> = {
555
styled: StyledFunction<Config>;
556
css: CssFunction<Config>;
557
globalCss: GlobalCssFunction<Config>;
558
keyframes: KeyframesFunction<Config>;
559
createTheme: CreateThemeFunction<Config>;
560
theme: ThemeInstance<Config>;
561
config: Config;
562
getCssText(): string;
563
reset(): void;
564
};
565
566
// Type-safe theme token access
567
type ThemeTokens<Theme> = {
568
[Scale in keyof Theme]: {
569
[Token in keyof Theme[Scale]]: string;
570
};
571
};
572
573
// Type-safe utility function parameters
574
type UtilityFunction<Config> = (value: any) => CSS<
575
Config['media'],
576
Config['theme'],
577
Config['themeMap'],
578
Config['utils']
579
>;
580
```
581
582
**Usage Examples:**
583
584
```typescript
585
// Fully typed configuration
586
const { styled } = createStitches({
587
theme: {
588
colors: {
589
primary: 'blue',
590
secondary: 'gray'
591
} as const,
592
space: {
593
sm: '8px',
594
md: '16px'
595
} as const
596
},
597
utils: {
598
px: (value: string) => ({
599
paddingLeft: value,
600
paddingRight: value
601
})
602
}
603
});
604
605
// TypeScript ensures token and utility existence
606
const TypedButton = styled('button', {
607
backgroundColor: '$colors$primary', // ✓ Valid
608
// backgroundColor: '$colors$invalid', // ✗ TypeScript error
609
px: '$space$md', // ✓ Valid utility with valid token
610
// px: '$space$invalid', // ✗ TypeScript error
611
});
612
```