MUI предоставляет мощный механизм для управления цветами и размерами
компонентов через тему. Центральным элементом является
объект createTheme, который позволяет определить кастомные
значения для:
Пример базового создания темы:
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: '#1976d2',
light: '#63a4ff',
dark: '#004ba0',
contrastText: '#fff',
},
secondary: {
main: '#dc004e',
},
},
typography: {
fontFamily: 'Roboto, Arial, sans-serif',
h1: { fontSize: '2.5rem' },
body1: { fontSize: '1rem' },
},
spacing: 8,
});
MUI разделяет цвета на основные (primary, secondary) и дополнительные (error, warning, info, success). Цвет можно задавать через объект палитры и использовать как:
color:<Button color="primary">Primary Button</Button>
<Button color="secondary">Secondary Button</Button>
sx или styled для более
точной настройки:import { Button } from '@mui/material';
<Button
sx={{
backgroundColor: 'primary.main',
color: 'primary.contrastText',
'&:hover': { backgroundColor: 'primary.dark' },
}}
>
Custom Button
</Button>
const theme = createTheme({
palette: {
tertiary: {
main: '#ff9800',
contrastText: '#000',
},
},
});
// Использовать через sx:
<Button sx={{ bgcolor: 'tertiary.main', color: 'tertiary.contrastText' }}>Tertiary</Button>
Размеры в MUI регулируются несколькими способами:
typography: {
h1: { fontSize: '3rem' },
h2: { fontSize: '2.5rem' },
body1: { fontSize: '1rem', lineHeight: 1.5 },
}
spacing). Например,
spacing(2) вернёт 16px при значении
spacing: 8.<Box sx={{ m: 2, p: 3 }}>Контент с отступами</Box>
m – marginp – paddingsize:<Button size="small">Small</Button>
<Button size="medium">Medium</Button>
<Button size="large">Large</Button>
TextField):<TextField size="small" variant="outlined" />
<TextField size="medium" variant="outlined" />
styled позволяет переопределить цвета и размеры
компонентов на уровне CSS с доступом к теме:
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';
const CustomButton = styled(Button)(({ theme }) => ({
backgroundColor: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
fontSize: theme.typography.h6.fontSize,
padding: theme.spacing(2),
'&:hover': {
backgroundColor: theme.palette.primary.dark,
},
}));
<CustomButton>Styled Button</CustomButton>
sx для динамических настроекsx — это shorthand-система для кастомизации компонентов
с доступом к теме и возможности задавать responsive-стили:
<Box
sx={{
bgcolor: 'secondary.main',
color: 'secondary.contrastText',
p: 2,
fontSize: { xs: '0.8rem', sm: '1rem', md: '1.2rem' },
'&:hover': { bgcolor: 'secondary.dark' },
}}
>
Адаптивный блок
</Box>
ThemeProviderДля применения кастомной палитры и размеров на всём приложении
используется ThemeProvider:
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
CssBaseline обеспечивает единообразные базовые
стили.sx или theme-пропы
(color, size), автоматически подхватывают
настройки темы.palette: {
success: {
main: '#4caf50',
contrastText: '#fff',
},
},
styled:const SuccessButton = styled(Button)(({ theme }) => ({
backgroundColor: theme.palette.success.main,
color: theme.palette.success.contrastText,
fontSize: theme.typography.body1.fontSize,
padding: theme.spacing(1, 3),
'&:hover': { backgroundColor: theme.palette.success.dark },
}));
<SuccessButton>Success</SuccessButton>
Такой подход обеспечивает консистентность цветов и размеров по всему проекту и упрощает последующую поддержку и масштабирование интерфейса.
MUI позволяет менять размеры и отступы в зависимости от экрана:
typography: {
h1: {
fontSize: '2rem',
[theme.breakpoints.up('sm')]: { fontSize: '2.5rem' },
[theme.breakpoints.up('md')]: { fontSize: '3rem' },
},
},
sx также поддерживает адаптивные свойства:
<Box
sx={{
p: { xs: 1, sm: 2, md: 4 },
fontSize: { xs: '0.9rem', sm: '1rem', md: '1.2rem' },
}}
>
Responsive content
</Box>
Эта система позволяет строить интерфейсы, которые динамически подстраиваются под размеры экрана без дублирования стилей.