0
# Styling & Theming
1
2
Comprehensive styling system with CSS-in-Python, responsive design, color modes, Radix UI theming, and design token integration for consistent and accessible user interfaces.
3
4
## Capabilities
5
6
### CSS-in-Python Styling
7
8
Type-safe CSS styling system with Python syntax, responsive design support, and automatic vendor prefixing for cross-browser compatibility.
9
10
```python { .api }
11
class Style:
12
"""
13
CSS styling management with responsive support and type safety.
14
15
Provides Python-based CSS styling with full CSS property support,
16
responsive breakpoints, pseudo-selectors, and automatic optimization.
17
"""
18
19
def __init__(self, **kwargs) -> None:
20
"""
21
Initialize style object with CSS properties.
22
23
Accepts any valid CSS property as keyword argument with
24
automatic camelCase to kebab-case conversion.
25
26
Args:
27
**kwargs: CSS properties and values
28
"""
29
...
30
31
def update(self, **kwargs) -> Style:
32
"""
33
Update style with additional CSS properties.
34
35
Args:
36
**kwargs: Additional CSS properties to merge
37
38
Returns:
39
Updated Style instance with merged properties
40
"""
41
...
42
43
def to_dict(self) -> dict[str, Any]:
44
"""
45
Convert style to dictionary representation.
46
47
Returns:
48
Dictionary of CSS properties and values
49
"""
50
...
51
52
# Common CSS Properties (examples)
53
color: str
54
background_color: str
55
font_size: str
56
margin: str
57
padding: str
58
width: str
59
height: str
60
display: str
61
flex_direction: str
62
justify_content: str
63
align_items: str
64
border: str
65
border_radius: str
66
box_shadow: str
67
transform: str
68
transition: str
69
opacity: float
70
z_index: int
71
```
72
73
Usage examples:
74
75
```python
76
# Basic styling
77
button_style = rx.Style(
78
background_color="blue",
79
color="white",
80
padding="10px 20px",
81
border_radius="4px",
82
border="none",
83
cursor="pointer"
84
)
85
86
# Responsive styling
87
responsive_style = rx.Style(
88
width="100%",
89
max_width={
90
"sm": "300px",
91
"md": "600px",
92
"lg": "900px"
93
},
94
font_size={
95
"base": "14px",
96
"md": "16px",
97
"lg": "18px"
98
}
99
)
100
101
# Component with styling
102
rx.button("Click me", style=button_style)
103
rx.box("Responsive content", style=responsive_style)
104
```
105
106
### Radix UI Theme System
107
108
Comprehensive theme system based on Radix UI design tokens with consistent color palettes, typography scales, and spacing systems.
109
110
```python { .api }
111
def theme(
112
accent_color: str = "indigo",
113
gray_color: str = "gray",
114
radius: str = "medium",
115
scaling: str = "100%",
116
panel_background: str = "solid",
117
appearance: str = "inherit",
118
**props
119
) -> Component:
120
"""
121
Theme provider component for consistent design system.
122
123
Wraps application with Radix UI theme providing design tokens,
124
color palettes, typography scales, and component styling.
125
126
Args:
127
accent_color: Primary accent color ('indigo', 'blue', 'red', etc.)
128
gray_color: Gray scale color palette ('gray', 'mauve', 'slate', etc.)
129
radius: Border radius scale ('none', 'small', 'medium', 'large', 'full')
130
scaling: Overall UI scaling factor ('90%', '95%', '100%', '105%', '110%')
131
panel_background: Panel background style ('solid', 'translucent')
132
appearance: Theme appearance ('inherit', 'light', 'dark')
133
**props: Additional theme configuration options
134
135
Returns:
136
Theme provider component wrapping application
137
"""
138
...
139
140
def theme_panel(**props) -> Component:
141
"""
142
Theme customization panel for runtime theme editing.
143
144
Provides interactive panel allowing users to customize theme
145
settings including colors, radius, and scaling in real-time.
146
147
Args:
148
**props: Panel styling and positioning options
149
150
Returns:
151
Interactive theme customization panel component
152
"""
153
...
154
```
155
156
Theme configuration example:
157
158
```python
159
def app():
160
return rx.theme(
161
rx.vstack(
162
rx.heading("My App"),
163
# ... app content ...
164
spacing="4"
165
),
166
accent_color="blue",
167
gray_color="slate",
168
radius="large",
169
scaling="105%"
170
)
171
```
172
173
### Color Mode Management
174
175
Dynamic color mode switching with system preference detection, persistent storage, and automatic component adaptation for light/dark themes.
176
177
```python { .api }
178
def color_mode() -> Component:
179
"""
180
Color mode provider for light/dark theme support.
181
182
Provides color mode context with system preference detection,
183
localStorage persistence, and automatic component adaptation.
184
185
Returns:
186
Color mode provider component for theme switching
187
"""
188
...
189
190
def toggle_color_mode() -> EventHandler:
191
"""
192
Event handler to toggle between light and dark modes.
193
194
Switches between light/dark themes with automatic persistence
195
to localStorage and smooth transitions between modes.
196
197
Returns:
198
EventHandler that toggles color mode when triggered
199
"""
200
...
201
202
def color_mode_cond(light: Component, dark: Component) -> Component:
203
"""
204
Conditional rendering based on current color mode.
205
206
Renders different components based on whether the current
207
theme is light or dark mode for mode-specific content.
208
209
Args:
210
light: Component to render in light mode
211
dark: Component to render in dark mode
212
213
Returns:
214
Conditional component that switches based on color mode
215
"""
216
...
217
```
218
219
Color mode usage:
220
221
```python
222
class ThemeState(rx.State):
223
def toggle_theme(self):
224
return rx.toggle_color_mode()
225
226
def theme_switcher():
227
return rx.hstack(
228
rx.color_mode_cond(
229
light=rx.icon("sun"),
230
dark=rx.icon("moon")
231
),
232
rx.button(
233
"Toggle Theme",
234
on_click=ThemeState.toggle_theme
235
)
236
)
237
```
238
239
### Responsive Design
240
241
Breakpoint system and responsive utilities for mobile-first design with automatic adaptation across device sizes.
242
243
```python { .api }
244
# Responsive breakpoint utilities
245
def desktop_only(*children, **props) -> Component:
246
"""
247
Show content only on desktop screens (1024px+).
248
249
Args:
250
*children: Components to show only on desktop
251
**props: Additional styling properties
252
253
Returns:
254
Component visible only on desktop screens
255
"""
256
...
257
258
def tablet_only(*children, **props) -> Component:
259
"""
260
Show content only on tablet screens (768px-1023px).
261
262
Args:
263
*children: Components to show only on tablets
264
**props: Additional styling properties
265
266
Returns:
267
Component visible only on tablet screens
268
"""
269
...
270
271
def mobile_only(*children, **props) -> Component:
272
"""
273
Show content only on mobile screens (0px-767px).
274
275
Args:
276
*children: Components to show only on mobile
277
**props: Additional styling properties
278
279
Returns:
280
Component visible only on mobile screens
281
"""
282
...
283
284
def mobile_and_tablet(*children, **props) -> Component:
285
"""
286
Show content on mobile and tablet screens (0px-1023px).
287
288
Args:
289
*children: Components to show on mobile and tablet
290
**props: Additional styling properties
291
292
Returns:
293
Component visible on mobile and tablet screens
294
"""
295
...
296
297
def tablet_and_desktop(*children, **props) -> Component:
298
"""
299
Show content on tablet and desktop screens (768px+).
300
301
Args:
302
*children: Components to show on tablet and desktop
303
**props: Additional styling properties
304
305
Returns:
306
Component visible on tablet and desktop screens
307
"""
308
...
309
310
# Breakpoint configuration
311
breakpoints = {
312
"sm": "30em", # 480px
313
"md": "48em", # 768px
314
"lg": "64em", # 1024px
315
"xl": "80em", # 1280px
316
"2xl": "96em" # 1536px
317
}
318
```
319
320
Responsive usage examples:
321
322
```python
323
def responsive_layout():
324
return rx.vstack(
325
# Responsive text sizing
326
rx.heading(
327
"Responsive Heading",
328
size={
329
"base": "md", # Mobile
330
"md": "lg", # Tablet
331
"lg": "xl" # Desktop
332
}
333
),
334
335
# Device-specific content
336
rx.desktop_only(
337
rx.text("This shows only on desktop")
338
),
339
rx.mobile_only(
340
rx.text("This shows only on mobile")
341
),
342
343
# Responsive grid
344
rx.grid(
345
rx.box("Item 1"),
346
rx.box("Item 2"),
347
rx.box("Item 3"),
348
columns={
349
"base": 1, # 1 column on mobile
350
"md": 2, # 2 columns on tablet
351
"lg": 3 # 3 columns on desktop
352
}
353
)
354
)
355
```
356
357
### Color System Integration
358
359
Comprehensive color management with semantic color tokens, accessibility compliance, and automatic contrast adjustment.
360
361
```python { .api }
362
def color(name: str, shade: int = 9) -> str:
363
"""
364
Access Radix UI color tokens with consistent palette.
365
366
Provides access to the complete Radix UI color system with
367
semantic color names and shade variations for consistent theming.
368
369
Args:
370
name: Color name ('blue', 'red', 'green', 'gray', etc.)
371
shade: Color shade from 1 (lightest) to 12 (darkest)
372
373
Returns:
374
CSS color value from Radix UI color system
375
"""
376
...
377
378
class Color:
379
"""
380
Color constants and utilities for consistent color usage.
381
382
Provides semantic color constants and utility functions for
383
working with colors in both light and dark theme contexts.
384
"""
385
386
# Semantic Colors
387
PRIMARY = "var(--accent-9)"
388
SECONDARY = "var(--gray-9)"
389
SUCCESS = "var(--green-9)"
390
WARNING = "var(--yellow-9)"
391
ERROR = "var(--red-9)"
392
INFO = "var(--blue-9)"
393
394
# Neutral Colors
395
WHITE = "var(--color-background)"
396
BLACK = "var(--gray-12)"
397
TRANSPARENT = "transparent"
398
399
@staticmethod
400
def with_alpha(color: str, alpha: float) -> str:
401
"""
402
Add alpha transparency to color.
403
404
Args:
405
color: Base color value
406
alpha: Transparency value (0.0 to 1.0)
407
408
Returns:
409
Color with applied alpha transparency
410
"""
411
...
412
413
@staticmethod
414
def contrast(color: str) -> str:
415
"""
416
Get appropriate contrast color for accessibility.
417
418
Args:
419
color: Background color to get contrast for
420
421
Returns:
422
High contrast color (light or dark) for accessibility
423
"""
424
...
425
```
426
427
Color usage examples:
428
429
```python
430
# Using color tokens
431
primary_button = rx.button(
432
"Primary Action",
433
style=rx.Style(
434
background_color=rx.color("blue", 9),
435
color=rx.color("blue", 1),
436
border=f"1px solid {rx.color('blue', 7)}"
437
)
438
)
439
440
# Semantic colors
441
success_alert = rx.callout(
442
"Success message",
443
color_scheme="green",
444
style=rx.Style(
445
background_color=rx.Color.SUCCESS + "20", # 20% alpha
446
border_left=f"4px solid {rx.Color.SUCCESS}"
447
)
448
)
449
```
450
451
### Custom Styling Patterns
452
453
Advanced styling patterns for animations, pseudo-selectors, and custom CSS properties for sophisticated user interfaces.
454
455
```python { .api }
456
# Advanced styling patterns
457
def create_animation_style(
458
name: str,
459
duration: str = "0.3s",
460
timing_function: str = "ease",
461
**keyframes
462
) -> Style:
463
"""
464
Create CSS animation with keyframes.
465
466
Args:
467
name: Animation name identifier
468
duration: Animation duration (e.g., "0.3s", "200ms")
469
timing_function: Animation timing ('ease', 'linear', 'ease-in-out')
470
**keyframes: Animation keyframe definitions
471
472
Returns:
473
Style object with animation configuration
474
"""
475
...
476
477
def hover_style(**kwargs) -> dict:
478
"""
479
Create hover state styling.
480
481
Args:
482
**kwargs: CSS properties to apply on hover
483
484
Returns:
485
Hover state style dictionary
486
"""
487
...
488
489
def focus_style(**kwargs) -> dict:
490
"""
491
Create focus state styling for accessibility.
492
493
Args:
494
**kwargs: CSS properties to apply on focus
495
496
Returns:
497
Focus state style dictionary
498
"""
499
...
500
501
def media_query(breakpoint: str, **kwargs) -> dict:
502
"""
503
Create responsive styles with media queries.
504
505
Args:
506
breakpoint: Breakpoint name or custom media query
507
**kwargs: CSS properties for the breakpoint
508
509
Returns:
510
Media query style dictionary
511
"""
512
...
513
```
514
515
Advanced styling example:
516
517
```python
518
# Custom button with hover and focus states
519
interactive_button = rx.button(
520
"Interactive Button",
521
style=rx.Style(
522
background="linear-gradient(45deg, blue, purple)",
523
color="white",
524
border="none",
525
padding="12px 24px",
526
border_radius="8px",
527
cursor="pointer",
528
transition="all 0.3s ease",
529
transform="translateY(0)",
530
box_shadow="0 4px 8px rgba(0,0,0,0.2)",
531
532
# Hover state
533
_hover={
534
"transform": "translateY(-2px)",
535
"box_shadow": "0 8px 16px rgba(0,0,0,0.3)"
536
},
537
538
# Focus state for accessibility
539
_focus={
540
"outline": "2px solid var(--accent-8)",
541
"outline_offset": "2px"
542
},
543
544
# Active state
545
_active={
546
"transform": "translateY(0)",
547
"box_shadow": "0 2px 4px rgba(0,0,0,0.2)"
548
}
549
)
550
)
551
```
552
553
## Usage Examples
554
555
### Complete Theme Setup
556
557
```python
558
import reflex as rx
559
560
def app():
561
return rx.theme(
562
rx.color_mode(
563
rx.vstack(
564
# Header with theme controls
565
rx.hstack(
566
rx.heading("My App"),
567
rx.spacer(),
568
rx.button(
569
rx.color_mode_cond(
570
light=rx.icon("moon"),
571
dark=rx.icon("sun")
572
),
573
on_click=rx.toggle_color_mode,
574
variant="ghost"
575
),
576
width="100%",
577
align="center"
578
),
579
580
# Main content
581
rx.container(
582
# ... app content ...
583
size="4"
584
),
585
586
spacing="6",
587
min_height="100vh"
588
)
589
),
590
# Theme configuration
591
accent_color="blue",
592
gray_color="slate",
593
radius="medium",
594
scaling="100%"
595
)
596
```
597
598
### Custom Component Styling
599
600
```python
601
def styled_card(title: str, content: str):
602
return rx.card(
603
rx.vstack(
604
rx.heading(title, size="md"),
605
rx.text(content),
606
spacing="3"
607
),
608
style=rx.Style(
609
padding="20px",
610
border_radius="12px",
611
box_shadow="0 4px 12px rgba(0,0,0,0.1)",
612
background="var(--color-surface)",
613
border="1px solid var(--gray-6)",
614
transition="all 0.2s ease",
615
616
_hover={
617
"transform": "translateY(-2px)",
618
"box_shadow": "0 8px 24px rgba(0,0,0,0.15)"
619
}
620
)
621
)
622
```
623
624
## Types
625
626
```python { .api }
627
from typing import Dict, Union, Any, Literal
628
629
# Style Types
630
CSSProperty = Union[str, int, float] # CSS property value
631
StyleDict = Dict[str, CSSProperty] # Style dictionary
632
ResponsiveValue = Union[CSSProperty, Dict[str, CSSProperty]] # Responsive values
633
634
# Color Types
635
ColorName = str # Color name from Radix UI palette
636
ColorShade = int # Color shade (1-12)
637
ColorValue = str # CSS color value
638
AlphaValue = float # Alpha transparency (0.0-1.0)
639
640
# Theme Types
641
AccentColor = Literal[
642
"gray", "gold", "bronze", "brown", "yellow", "amber", "orange",
643
"tomato", "red", "ruby", "crimson", "pink", "plum", "purple",
644
"violet", "iris", "indigo", "blue", "cyan", "teal", "jade",
645
"green", "grass", "lime", "mint", "sky"
646
]
647
648
GrayColor = Literal["gray", "mauve", "slate", "sage", "olive", "sand"]
649
Radius = Literal["none", "small", "medium", "large", "full"]
650
Scaling = Literal["90%", "95%", "100%", "105%", "110%"]
651
652
# Responsive Types
653
Breakpoint = Literal["base", "sm", "md", "lg", "xl", "2xl"]
654
MediaQuery = str # CSS media query string
655
656
# Animation Types
657
AnimationDuration = str # Animation duration (e.g., "0.3s", "200ms")
658
TimingFunction = Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]
659
TransformValue = str # CSS transform value
660
661
# Pseudo-selector Types
662
PseudoSelector = Literal[
663
"_hover", "_focus", "_active", "_disabled", "_visited",
664
"_first_child", "_last_child", "_odd", "_even"
665
]
666
```