0
# CSS Classes
1
2
Generate CSS classes with variants and compound variants for maximum flexibility. The `css` function creates reusable CSS classes that can be applied to any element or component without React component overhead.
3
4
## Capabilities
5
6
### CSS Function
7
8
Creates CSS classes with variants and compound variants for reusable styling.
9
10
```typescript { .api }
11
/**
12
* Creates a CSS class with optional variants and compound variants
13
* @param composers - Style objects, strings, functions, or other components to compose
14
* @returns CSS component function with className and selector properties
15
*/
16
function css<
17
Composers extends Array<string | React.ComponentType<any> | Function | { [name: string]: unknown }>
18
>(
19
...composers: Composers
20
): CssComponent<'span', StyledComponentProps<Composers>, {}, CSS>;
21
22
interface CssComponent<Type = 'span', Props = {}, Media = {}, CSS = {}> {
23
/** Apply CSS class with optional variant props and responsive variants */
24
(props?: TransformProps<Props, Media> & { css?: CSS } & { [name: string]: any }):
25
string & { className: string; selector: string; props: any };
26
27
/** CSS class name generated for this style */
28
className: string;
29
/** CSS selector for targeting this class */
30
selector: string;
31
32
/** Internal symbols for type extraction */
33
[$$StyledComponentType]: Type;
34
[$$StyledComponentProps]: Props;
35
[$$StyledComponentMedia]: Media;
36
}
37
38
type StyledComponentProps<Composers extends readonly unknown[]> =
39
Composers extends readonly [infer First, ...infer Rest]
40
? First extends { variants?: infer V }
41
? V & StyledComponentProps<Rest>
42
: StyledComponentProps<Rest>
43
: {};
44
45
type TransformProps<Props, Media> = {
46
[K in keyof Props]: (
47
| Props[K]
48
| (
49
& { [KMedia in `@${keyof Media | 'initial'}`]?: Props[K] }
50
& { [KMedia in string]: Props[K] }
51
)
52
);
53
};
54
```
55
56
**Usage Examples:**
57
58
```typescript
59
import { css, CSS, TransformProps, StyledComponentProps, $$StyledComponentType, $$StyledComponentProps, $$StyledComponentMedia } from "@stitches/react";
60
61
// Basic CSS class
62
const buttonStyles = css({
63
padding: '12px 16px',
64
borderRadius: '4px',
65
border: 'none',
66
cursor: 'pointer',
67
backgroundColor: 'blue',
68
color: 'white'
69
});
70
71
// Apply to JSX elements
72
function Button({ children }) {
73
return <button className={buttonStyles()}>{children}</button>;
74
}
75
76
// Or get just the class name
77
const className = buttonStyles.className;
78
```
79
80
### CSS Classes with Variants
81
82
Create CSS classes with multiple style variations controlled by props.
83
84
```typescript { .api }
85
interface CssVariantConfig {
86
variants?: {
87
[variantName: string]: {
88
[variantValue: string | number]: StyleObject;
89
};
90
};
91
compoundVariants?: Array<{
92
[variantName: string]: string | number;
93
css: StyleObject;
94
}>;
95
defaultVariants?: {
96
[variantName: string]: string | number;
97
};
98
}
99
```
100
101
**Usage Examples:**
102
103
```typescript
104
const cardStyles = css({
105
padding: '16px',
106
backgroundColor: 'white',
107
borderRadius: '8px',
108
109
variants: {
110
size: {
111
small: { padding: '12px', fontSize: '14px' },
112
medium: { padding: '16px', fontSize: '16px' },
113
large: { padding: '24px', fontSize: '18px' }
114
},
115
elevation: {
116
flat: { boxShadow: 'none' },
117
low: { boxShadow: '0 2px 4px rgba(0,0,0,0.1)' },
118
high: { boxShadow: '0 8px 16px rgba(0,0,0,0.15)' }
119
},
120
color: {
121
neutral: { backgroundColor: 'white' },
122
primary: { backgroundColor: 'lightblue' },
123
success: { backgroundColor: 'lightgreen' },
124
warning: { backgroundColor: 'lightyellow' },
125
danger: { backgroundColor: 'lightcoral' }
126
}
127
},
128
129
compoundVariants: [
130
{
131
size: 'large',
132
elevation: 'high',
133
css: { padding: '32px' }
134
}
135
],
136
137
defaultVariants: {
138
size: 'medium',
139
elevation: 'low',
140
color: 'neutral'
141
}
142
});
143
144
// Usage with variant props
145
function Card({ size, elevation, color, children }) {
146
return (
147
<div className={cardStyles({ size, elevation, color })}>
148
{children}
149
</div>
150
);
151
}
152
153
// Or apply specific variants
154
<div className={cardStyles({ size: 'large', color: 'primary' })}>
155
Large primary card
156
</div>
157
```
158
159
### CSS Class Composition
160
161
Compose multiple CSS classes together for complex styling.
162
163
**Usage Examples:**
164
165
```typescript
166
const baseBox = css({
167
padding: '16px',
168
borderRadius: '4px'
169
});
170
171
const coloredBox = css(baseBox, {
172
backgroundColor: 'lightblue',
173
border: '1px solid blue'
174
});
175
176
const interactiveBox = css(coloredBox, {
177
cursor: 'pointer',
178
transition: 'all 0.2s ease',
179
180
'&:hover': {
181
backgroundColor: 'blue',
182
color: 'white'
183
}
184
});
185
186
// Use composed classes
187
<div className={interactiveBox()}>
188
Interactive colored box
189
</div>
190
```
191
192
### Responsive CSS Classes
193
194
Apply different styles based on media queries within CSS classes.
195
196
**Usage Examples:**
197
198
```typescript
199
const responsiveGrid = css({
200
display: 'grid',
201
gap: '16px',
202
gridTemplateColumns: '1fr',
203
204
'@media (min-width: 768px)': {
205
gridTemplateColumns: 'repeat(2, 1fr)',
206
gap: '24px'
207
},
208
209
'@media (min-width: 1024px)': {
210
gridTemplateColumns: 'repeat(3, 1fr)',
211
gap: '32px'
212
}
213
});
214
215
// Or use configured breakpoints
216
const responsiveText = css({
217
fontSize: '16px',
218
lineHeight: 1.4,
219
220
'@bp2': {
221
fontSize: '18px',
222
lineHeight: 1.5
223
},
224
225
'@bp3': {
226
fontSize: '20px',
227
lineHeight: 1.6
228
}
229
});
230
```
231
232
### Dynamic CSS Classes
233
234
Generate CSS classes dynamically based on runtime conditions.
235
236
**Usage Examples:**
237
238
```typescript
239
const dynamicButton = css({
240
padding: '12px 16px',
241
border: 'none',
242
borderRadius: '4px',
243
cursor: 'pointer',
244
245
variants: {
246
theme: {
247
light: {
248
backgroundColor: 'white',
249
color: 'black',
250
border: '1px solid gray'
251
},
252
dark: {
253
backgroundColor: 'black',
254
color: 'white',
255
border: '1px solid gray'
256
}
257
},
258
loading: {
259
true: {
260
opacity: 0.6,
261
cursor: 'not-allowed',
262
pointerEvents: 'none'
263
}
264
}
265
}
266
});
267
268
function DynamicButton({ theme, loading, children, ...props }) {
269
return (
270
<button
271
className={dynamicButton({ theme, loading })}
272
{...props}
273
>
274
{loading ? 'Loading...' : children}
275
</button>
276
);
277
}
278
```
279
280
### CSS Class Utilities
281
282
Work with CSS class metadata and selectors for advanced use cases.
283
284
**Usage Examples:**
285
286
```typescript
287
const myStyles = css({
288
color: 'blue',
289
padding: '16px'
290
});
291
292
// Get class name for external use
293
const className = myStyles.className;
294
console.log(className); // "c-abc123"
295
296
// Get CSS selector
297
const selector = myStyles.selector;
298
console.log(selector); // ".c-abc123"
299
300
// Use in CSS-in-JS libraries or global styles
301
const globalStyles = css({
302
[`${myStyles.selector}:hover`]: {
303
color: 'red'
304
}
305
});
306
```
307
308
### CSS Variables and Custom Properties
309
310
Use CSS custom properties and variables within CSS classes.
311
312
**Usage Examples:**
313
314
```typescript
315
const themedComponent = css({
316
'--primary-color': 'blue',
317
'--spacing': '16px',
318
319
backgroundColor: 'var(--primary-color)',
320
padding: 'var(--spacing)',
321
322
variants: {
323
theme: {
324
dark: {
325
'--primary-color': 'darkblue',
326
'--spacing': '20px'
327
}
328
}
329
}
330
});
331
332
// CSS custom properties work with theme tokens
333
const tokenBasedStyles = css({
334
'--card-bg': '$colors$cardBackground',
335
'--card-padding': '$space$4',
336
337
backgroundColor: 'var(--card-bg)',
338
padding: 'var(--card-padding)'
339
});
340
```
341
342
## Type Safety
343
344
```typescript { .api }
345
// Extract variant props from CSS component
346
type VariantProps<CssComponent> = CssComponent extends (props: infer P) => any
347
? P
348
: never;
349
350
// CSS component function signature
351
interface CssComponentFunction<Props = {}> {
352
(props?: Props): string & {
353
className: string;
354
selector: string;
355
props: Props;
356
};
357
}
358
```
359
360
**Usage Examples:**
361
362
```typescript
363
const styledCard = css({
364
variants: {
365
size: { small: {}, large: {} },
366
color: { primary: {}, secondary: {} }
367
}
368
});
369
370
// Extract variant props type
371
type CardProps = VariantProps<typeof styledCard>;
372
// CardProps = { size?: 'small' | 'large'; color?: 'primary' | 'secondary' }
373
374
// Use in component props
375
interface MyCardProps extends CardProps {
376
title: string;
377
children: React.ReactNode;
378
}
379
380
function MyCard({ title, children, ...styleProps }: MyCardProps) {
381
return (
382
<div className={styledCard(styleProps)}>
383
<h3>{title}</h3>
384
{children}
385
</div>
386
);
387
}
388
```