The sx Prop - Detailed Guide
The sx prop is a powerful shortcut for defining custom styles with access to the theme. It provides a superset of CSS with additional features for responsive design and theme integration.
Implementation
Thesx prop is powered by the styleFunctionSx from styleFunctionSx.js:78-141:
Basic Usage
Object Syntax
Function Syntax
Access the theme directly:Array Syntax
Combine multiple style objects:Theme Access
Palette
Access palette colors using dot notation:defaultSxConfig.js:69-81:
Spacing
Use spacing scale with shorthand properties:Typography
Access typography settings:Breakpoints
Reference breakpoint values:Shadows
Use theme shadows:Border Radius
Apply theme border radius:Responsive Styles
Object Syntax
Define styles for specific breakpoints:Array Syntax (Mobile-First)
Provide values in ascending breakpoint order:Mixed Responsive Values
CSS Properties
All Standard CSS
All CSS properties are supported:Shorthand Properties
Fromspacing.js:7-26:
m, mt, mr, mb, ml, mx, my- Marginp, pt, pr, pb, pl, px, py- Paddingbgcolor- Background color
Pseudo-Selectors
Hover and Focus
Active and Disabled
Other Pseudo-Selectors
Nested Selectors
Child Selectors
Descendant Selectors
Media Queries
Custom Media Queries
Print Styles
displayPrint shorthand from defaultSxConfig.js:207-214:
Advanced Patterns
Conditional Styles
Combining with Props
Dynamic Theme Values
TypeScript
SxProps Type
Type-safe Theme Access
Component Props with sx
Performance Considerations
Memoization
Styles are automatically memoized, but you can optimize further:Static Styles
Define static styles outside components:Configuration
Thesx prop behavior is configured via defaultSxConfig from defaultSxConfig.js. You can customize it:
Best Practices
- Use theme values - Always reference theme for consistency
- Prefer object syntax - More readable than function syntax
- Extract common styles - Define reusable style objects
- Use responsive objects - Clearer than arrays for responsive design
- Leverage TypeScript - Type safety prevents errors
- Memoize dynamic styles - Optimize re-renders
- Keep it simple - Complex styles may be better in
styled()
Related
- Box Component - Primary component using sx
- styled() API - For complex reusable components
- Breakpoints - Responsive design guide