Material UI (MUI) styling solutions
1. Default Theme with sx Prop
The sx prop is MUI's most powerful and preferred styling solution. It allows you to apply styles directly to a component using a CSS-like syntax but with access to the theme's values (e.g., colors, typography, spacing).
Example:
import { Box } from '@mui/material';
function App() {
return (
<Box sx={{
backgroundColor: 'primary.main',
color: 'white',
p: 2, // padding (uses theme.spacing)
borderRadius: 2, // uses theme's borderRadius
textAlign: 'center'
zIndex: (theme) => theme.zIndex.paywall // uses theme's zIndex object
}}>Hello, Material-UI!</Box>
);
}
- Advantages:
- Simple and intuitive.
- Full access to the theme.
- Can be used inline without defining external classes or styles.
2. Custom Themes (ThemeProvider)
MUI provides a theming system that lets you customize global styles such as colors, typography, spacing, and components.
Example:
import { createTheme, ThemeProvider, Button } from '@mui/material';
const theme = createTheme({
palette: {
primary: {
main: '#1976d2', // Custom primary color
},
},
typography: { fontFamily: 'Poppins, sans-serif' },
});
function App() {
return (
<ThemeProvider theme={theme}>
<Button variant="contained" color="primary">Themed Button</Button>
</ThemeProvider>
);
}
- Advantages:
- Centralized control of styles (e.g., colors, typography).
- Promotes consistency across your app.
3. Styled API
The styled utility, built on Emotion, allows you to create custom styled components with scoped styles. It supports both dynamic and static styles.
Example:
import { styled } from '@mui/material';
const CustomButton = styled('button')(({ theme }) => ({
backgroundColor: theme.palette.primary.main,
color: 'white',
padding: theme.spacing(1, 2),
border: 'none',
borderRadius: theme.shape.borderRadius,
cursor: 'pointer',
'&:hover': { backgroundColor: theme.palette.primary.dark },
})
);
function App() { return <CustomButton>Styled Button</CustomButton>; }`
- Advantages:
- Full control over the styling of components.
- Integrates seamlessly with the MUI theme.
- Avoids class name conflicts (styles are scoped).
4. Global CSS with CssBaseline
5. Utility Classes with makeStyles and withStyles
MUI previously used makeStyles and withStyles (based on JSS) to create CSS-like styling with classes. These utilities are now deprecated in MUI v5 in favor of the styled API and sx prop.
6. Integration with Tailwind or Plain CSS
If you prefer using CSS frameworks like Tailwind CSS or writing plain CSS, MUI components support className and can integrate easily.