Web apps in pure Python with reactive components and automatic frontend generation.
—
Comprehensive styling system with CSS-in-Python, responsive design, color modes, Radix UI theming, and design token integration for consistent and accessible user interfaces.
Type-safe CSS styling system with Python syntax, responsive design support, and automatic vendor prefixing for cross-browser compatibility.
class Style:
"""
CSS styling management with responsive support and type safety.
Provides Python-based CSS styling with full CSS property support,
responsive breakpoints, pseudo-selectors, and automatic optimization.
"""
def __init__(self, **kwargs) -> None:
"""
Initialize style object with CSS properties.
Accepts any valid CSS property as keyword argument with
automatic camelCase to kebab-case conversion.
Args:
**kwargs: CSS properties and values
"""
...
def update(self, **kwargs) -> Style:
"""
Update style with additional CSS properties.
Args:
**kwargs: Additional CSS properties to merge
Returns:
Updated Style instance with merged properties
"""
...
def to_dict(self) -> dict[str, Any]:
"""
Convert style to dictionary representation.
Returns:
Dictionary of CSS properties and values
"""
...
# Common CSS Properties (examples)
color: str
background_color: str
font_size: str
margin: str
padding: str
width: str
height: str
display: str
flex_direction: str
justify_content: str
align_items: str
border: str
border_radius: str
box_shadow: str
transform: str
transition: str
opacity: float
z_index: intUsage examples:
# Basic styling
button_style = rx.Style(
background_color="blue",
color="white",
padding="10px 20px",
border_radius="4px",
border="none",
cursor="pointer"
)
# Responsive styling
responsive_style = rx.Style(
width="100%",
max_width={
"sm": "300px",
"md": "600px",
"lg": "900px"
},
font_size={
"base": "14px",
"md": "16px",
"lg": "18px"
}
)
# Component with styling
rx.button("Click me", style=button_style)
rx.box("Responsive content", style=responsive_style)Comprehensive theme system based on Radix UI design tokens with consistent color palettes, typography scales, and spacing systems.
def theme(
accent_color: str = "indigo",
gray_color: str = "gray",
radius: str = "medium",
scaling: str = "100%",
panel_background: str = "solid",
appearance: str = "inherit",
**props
) -> Component:
"""
Theme provider component for consistent design system.
Wraps application with Radix UI theme providing design tokens,
color palettes, typography scales, and component styling.
Args:
accent_color: Primary accent color ('indigo', 'blue', 'red', etc.)
gray_color: Gray scale color palette ('gray', 'mauve', 'slate', etc.)
radius: Border radius scale ('none', 'small', 'medium', 'large', 'full')
scaling: Overall UI scaling factor ('90%', '95%', '100%', '105%', '110%')
panel_background: Panel background style ('solid', 'translucent')
appearance: Theme appearance ('inherit', 'light', 'dark')
**props: Additional theme configuration options
Returns:
Theme provider component wrapping application
"""
...
def theme_panel(**props) -> Component:
"""
Theme customization panel for runtime theme editing.
Provides interactive panel allowing users to customize theme
settings including colors, radius, and scaling in real-time.
Args:
**props: Panel styling and positioning options
Returns:
Interactive theme customization panel component
"""
...Theme configuration example:
def app():
return rx.theme(
rx.vstack(
rx.heading("My App"),
# ... app content ...
spacing="4"
),
accent_color="blue",
gray_color="slate",
radius="large",
scaling="105%"
)Dynamic color mode switching with system preference detection, persistent storage, and automatic component adaptation for light/dark themes.
def color_mode() -> Component:
"""
Color mode provider for light/dark theme support.
Provides color mode context with system preference detection,
localStorage persistence, and automatic component adaptation.
Returns:
Color mode provider component for theme switching
"""
...
def toggle_color_mode() -> EventHandler:
"""
Event handler to toggle between light and dark modes.
Switches between light/dark themes with automatic persistence
to localStorage and smooth transitions between modes.
Returns:
EventHandler that toggles color mode when triggered
"""
...
def color_mode_cond(light: Component, dark: Component) -> Component:
"""
Conditional rendering based on current color mode.
Renders different components based on whether the current
theme is light or dark mode for mode-specific content.
Args:
light: Component to render in light mode
dark: Component to render in dark mode
Returns:
Conditional component that switches based on color mode
"""
...Color mode usage:
class ThemeState(rx.State):
def toggle_theme(self):
return rx.toggle_color_mode()
def theme_switcher():
return rx.hstack(
rx.color_mode_cond(
light=rx.icon("sun"),
dark=rx.icon("moon")
),
rx.button(
"Toggle Theme",
on_click=ThemeState.toggle_theme
)
)Breakpoint system and responsive utilities for mobile-first design with automatic adaptation across device sizes.
# Responsive breakpoint utilities
def desktop_only(*children, **props) -> Component:
"""
Show content only on desktop screens (1024px+).
Args:
*children: Components to show only on desktop
**props: Additional styling properties
Returns:
Component visible only on desktop screens
"""
...
def tablet_only(*children, **props) -> Component:
"""
Show content only on tablet screens (768px-1023px).
Args:
*children: Components to show only on tablets
**props: Additional styling properties
Returns:
Component visible only on tablet screens
"""
...
def mobile_only(*children, **props) -> Component:
"""
Show content only on mobile screens (0px-767px).
Args:
*children: Components to show only on mobile
**props: Additional styling properties
Returns:
Component visible only on mobile screens
"""
...
def mobile_and_tablet(*children, **props) -> Component:
"""
Show content on mobile and tablet screens (0px-1023px).
Args:
*children: Components to show on mobile and tablet
**props: Additional styling properties
Returns:
Component visible on mobile and tablet screens
"""
...
def tablet_and_desktop(*children, **props) -> Component:
"""
Show content on tablet and desktop screens (768px+).
Args:
*children: Components to show on tablet and desktop
**props: Additional styling properties
Returns:
Component visible on tablet and desktop screens
"""
...
# Breakpoint configuration
breakpoints = {
"sm": "30em", # 480px
"md": "48em", # 768px
"lg": "64em", # 1024px
"xl": "80em", # 1280px
"2xl": "96em" # 1536px
}Responsive usage examples:
def responsive_layout():
return rx.vstack(
# Responsive text sizing
rx.heading(
"Responsive Heading",
size={
"base": "md", # Mobile
"md": "lg", # Tablet
"lg": "xl" # Desktop
}
),
# Device-specific content
rx.desktop_only(
rx.text("This shows only on desktop")
),
rx.mobile_only(
rx.text("This shows only on mobile")
),
# Responsive grid
rx.grid(
rx.box("Item 1"),
rx.box("Item 2"),
rx.box("Item 3"),
columns={
"base": 1, # 1 column on mobile
"md": 2, # 2 columns on tablet
"lg": 3 # 3 columns on desktop
}
)
)Comprehensive color management with semantic color tokens, accessibility compliance, and automatic contrast adjustment.
def color(name: str, shade: int = 9) -> str:
"""
Access Radix UI color tokens with consistent palette.
Provides access to the complete Radix UI color system with
semantic color names and shade variations for consistent theming.
Args:
name: Color name ('blue', 'red', 'green', 'gray', etc.)
shade: Color shade from 1 (lightest) to 12 (darkest)
Returns:
CSS color value from Radix UI color system
"""
...
class Color:
"""
Color constants and utilities for consistent color usage.
Provides semantic color constants and utility functions for
working with colors in both light and dark theme contexts.
"""
# Semantic Colors
PRIMARY = "var(--accent-9)"
SECONDARY = "var(--gray-9)"
SUCCESS = "var(--green-9)"
WARNING = "var(--yellow-9)"
ERROR = "var(--red-9)"
INFO = "var(--blue-9)"
# Neutral Colors
WHITE = "var(--color-background)"
BLACK = "var(--gray-12)"
TRANSPARENT = "transparent"
@staticmethod
def with_alpha(color: str, alpha: float) -> str:
"""
Add alpha transparency to color.
Args:
color: Base color value
alpha: Transparency value (0.0 to 1.0)
Returns:
Color with applied alpha transparency
"""
...
@staticmethod
def contrast(color: str) -> str:
"""
Get appropriate contrast color for accessibility.
Args:
color: Background color to get contrast for
Returns:
High contrast color (light or dark) for accessibility
"""
...Color usage examples:
# Using color tokens
primary_button = rx.button(
"Primary Action",
style=rx.Style(
background_color=rx.color("blue", 9),
color=rx.color("blue", 1),
border=f"1px solid {rx.color('blue', 7)}"
)
)
# Semantic colors
success_alert = rx.callout(
"Success message",
color_scheme="green",
style=rx.Style(
background_color=rx.Color.SUCCESS + "20", # 20% alpha
border_left=f"4px solid {rx.Color.SUCCESS}"
)
)Advanced styling patterns for animations, pseudo-selectors, and custom CSS properties for sophisticated user interfaces.
# Advanced styling patterns
def create_animation_style(
name: str,
duration: str = "0.3s",
timing_function: str = "ease",
**keyframes
) -> Style:
"""
Create CSS animation with keyframes.
Args:
name: Animation name identifier
duration: Animation duration (e.g., "0.3s", "200ms")
timing_function: Animation timing ('ease', 'linear', 'ease-in-out')
**keyframes: Animation keyframe definitions
Returns:
Style object with animation configuration
"""
...
def hover_style(**kwargs) -> dict:
"""
Create hover state styling.
Args:
**kwargs: CSS properties to apply on hover
Returns:
Hover state style dictionary
"""
...
def focus_style(**kwargs) -> dict:
"""
Create focus state styling for accessibility.
Args:
**kwargs: CSS properties to apply on focus
Returns:
Focus state style dictionary
"""
...
def media_query(breakpoint: str, **kwargs) -> dict:
"""
Create responsive styles with media queries.
Args:
breakpoint: Breakpoint name or custom media query
**kwargs: CSS properties for the breakpoint
Returns:
Media query style dictionary
"""
...Advanced styling example:
# Custom button with hover and focus states
interactive_button = rx.button(
"Interactive Button",
style=rx.Style(
background="linear-gradient(45deg, blue, purple)",
color="white",
border="none",
padding="12px 24px",
border_radius="8px",
cursor="pointer",
transition="all 0.3s ease",
transform="translateY(0)",
box_shadow="0 4px 8px rgba(0,0,0,0.2)",
# Hover state
_hover={
"transform": "translateY(-2px)",
"box_shadow": "0 8px 16px rgba(0,0,0,0.3)"
},
# Focus state for accessibility
_focus={
"outline": "2px solid var(--accent-8)",
"outline_offset": "2px"
},
# Active state
_active={
"transform": "translateY(0)",
"box_shadow": "0 2px 4px rgba(0,0,0,0.2)"
}
)
)import reflex as rx
def app():
return rx.theme(
rx.color_mode(
rx.vstack(
# Header with theme controls
rx.hstack(
rx.heading("My App"),
rx.spacer(),
rx.button(
rx.color_mode_cond(
light=rx.icon("moon"),
dark=rx.icon("sun")
),
on_click=rx.toggle_color_mode,
variant="ghost"
),
width="100%",
align="center"
),
# Main content
rx.container(
# ... app content ...
size="4"
),
spacing="6",
min_height="100vh"
)
),
# Theme configuration
accent_color="blue",
gray_color="slate",
radius="medium",
scaling="100%"
)def styled_card(title: str, content: str):
return rx.card(
rx.vstack(
rx.heading(title, size="md"),
rx.text(content),
spacing="3"
),
style=rx.Style(
padding="20px",
border_radius="12px",
box_shadow="0 4px 12px rgba(0,0,0,0.1)",
background="var(--color-surface)",
border="1px solid var(--gray-6)",
transition="all 0.2s ease",
_hover={
"transform": "translateY(-2px)",
"box_shadow": "0 8px 24px rgba(0,0,0,0.15)"
}
)
)from typing import Dict, Union, Any, Literal
# Style Types
CSSProperty = Union[str, int, float] # CSS property value
StyleDict = Dict[str, CSSProperty] # Style dictionary
ResponsiveValue = Union[CSSProperty, Dict[str, CSSProperty]] # Responsive values
# Color Types
ColorName = str # Color name from Radix UI palette
ColorShade = int # Color shade (1-12)
ColorValue = str # CSS color value
AlphaValue = float # Alpha transparency (0.0-1.0)
# Theme Types
AccentColor = Literal[
"gray", "gold", "bronze", "brown", "yellow", "amber", "orange",
"tomato", "red", "ruby", "crimson", "pink", "plum", "purple",
"violet", "iris", "indigo", "blue", "cyan", "teal", "jade",
"green", "grass", "lime", "mint", "sky"
]
GrayColor = Literal["gray", "mauve", "slate", "sage", "olive", "sand"]
Radius = Literal["none", "small", "medium", "large", "full"]
Scaling = Literal["90%", "95%", "100%", "105%", "110%"]
# Responsive Types
Breakpoint = Literal["base", "sm", "md", "lg", "xl", "2xl"]
MediaQuery = str # CSS media query string
# Animation Types
AnimationDuration = str # Animation duration (e.g., "0.3s", "200ms")
TimingFunction = Literal["ease", "ease-in", "ease-out", "ease-in-out", "linear"]
TransformValue = str # CSS transform value
# Pseudo-selector Types
PseudoSelector = Literal[
"_hover", "_focus", "_active", "_disabled", "_visited",
"_first_child", "_last_child", "_odd", "_even"
]Install with Tessl CLI
npx tessl i tessl/pypi-reflex