Палитра
The palette enables you to modify the color of the components to suit your brand.
Palette colors
The theme exposes the following palette colors (accessible under theme.palette.
):
- primary - Основной. Используется для отображения основных элементов интерфейса It's the color displayed most frequently across your app's screens and components.
- secondary - Второстепенный. Используется для отображения второстепенных элементов интерфейса. It provides more ways to accent and distinguish your product. Having it is optional.
- error - Цвет ошибки. Используется для отображения элементов, на которые нужно обратить внимание.
- *Предупреждение. Используется для отображения потенциально опасных действия или важных сообщений.
- info - Информация. Используется для отображения нейтральной, не представляющей особой важности информации.
- success - Успешно. Используется для оповещения об успешном завершении вызванного пользователем действия.
Для более подробного изучения цветовых настроек можно посетить секцию про цвета.
Default values
You can explore the default values of the palette using the theme explorer or by opening the dev tools console on this page (window.theme.palette
).
Primary
palette.primary.light
#42a5f5
palette.primary.main
#1976d2
palette.primary.dark
#1565c0
Secondary
palette.secondary.light
#ba68c8
palette.secondary.main
#9c27b0
palette.secondary.dark
#7b1fa2
Error
palette.error.light
#ef5350
palette.error.main
#d32f2f
palette.error.dark
#c62828
Warning
palette.warning.light
#ffb74d
palette.warning.main
#ff9800
palette.warning.dark
#f57c00
Info
palette.info.light
#4dd0e1
palette.info.main
#00bcd4
palette.info.dark
#0097a7
Success
palette.success.light
#81c784
palette.success.main
#4caf50
palette.success.dark
#388e3c
Стандартная палитра использует оттенки с префиксом A
(A200
, и т. д.) - для вторичного оттенка, и без префикса - для всех остальных.
Кастомизация
You may override the default palette values by including a palette object as part of your theme. If any of the:
переопределенные цвета палитры заменят стандартные.
The palette color value can either be a color object, or an object with one or more of the keys specified by the following TypeScript interface:
interface PaletteColor {
light?: string;
main: string;
dark?: string;
contrastText?: string;
}
Using a color object
Простейший способ переопределить цветовую палитру - импортировать один или несколько существующих цветов и применить их.
import { createTheme } from '@material-ui/core/styles';
import blue from '@material-ui/core/colors/blue';
const theme = createTheme({
palette: {
primary: blue,
},
});
Providing the colors directly
Для создания палитры с большим количеством цветов вы можете либо создать свой собственный цвет, либо записать цвета напрямую в один или все ключи тематической палитры
import { createTheme } from '@material-ui/core/styles';
const theme = createTheme({
palette: {
primary: {
// light: will be calculated from palette.primary.main,
main: '#ff4400',
// dark: will be calculated from palette.primary.main,
// contrastText: will be calculated to contrast with palette.primary.main
},
secondary: {
light: '#0066ff',
main: '#0044ff',
// dark: will be calculated from palette.secondary.main,
contrastText: '#ffcc00',
},
// Used by `getContrastText()` to maximize the contrast between
// the background and the text.
tonalOffset: 0.2,
},
});
contrastThreshold: 3,
// Used by the functions below to shift a color's luminance by approximately
// two indexes within its tonal palette.
tonalOffset: 0.2,
},
});
contrastThreshold: 3,
// Used by the functions below to shift a color's luminance by approximately
// two indexes within its tonal palette.
// E.g., shift from Red 500 to Red 300 or Red 700.
В примере выше, если палитра содержит пользовательские цвета с одним из следующих ключей: "main", "light", "dark" или"contrastText", они используются следующим образом:
- If the "dark" and / or "light" keys are omitted, their value(s) will be calculated from "main", according to the "tonalOffset" value.
- If "contrastText" is omitted, its value will be calculated to contrast with "main", according to the "contrastThreshold" value.
Both the "tonalOffset" and "contrastThreshold" values may be customized as needed. The "tonalOffset" value can either be a number between 0 and 1, which will apply to both light and dark variants, or an object with light and dark variants specified by the following TypeScript type:
type PaletteTonalOffset = number | {
light: number;
dark: number;
};
A higher value for "tonalOffset" will make calculated values for "light" lighter, and "dark" darker. A higher value for "contrastThreshold" increases the point at which a background color is considered light, and given a dark "contrastText".
Note that "contrastThreshold" follows a non-linear curve.
Пример
import * as React from 'react';
import { createTheme, ThemeProvider } from '@material-ui/core/styles';
import { purple } from '@material-ui/core/colors';
import Button from '@material-ui/core/Button';
const theme = createTheme({
palette: {
primary: {
// Purple and green play nicely together.
main: purple[500],
},
secondary: {
// This is green.A700 as hex.
main: '#11cb5f',
},
},
});
export default function Palette() {
return (
<ThemeProvider theme={theme}>
<Button>Primary</Button>
<Button color="secondary">Secondary</Button>
</ThemeProvider>
);
}
Adding new colors
You can add new colors inside and outside the palette of the theme as follow:
import { createTheme } from '@material-ui/core/styles';
const theme = createTheme({
status: {
danger: '#e53e3e',
},
palette: {
primary: {
main: '#0971f1',
darker: '#053e85',
},
neutral: {
main: '#64748B',
contrastText: '#fff',
},
},
});
If you are using TypeScript, you would also need to use module augmentation for the theme to accept the above values.
declare module '@material-ui/core/styles/createMuiTheme' {
interface Theme {
status: {
danger: React.CSSProperties['color'],
}
}
interface ThemeOptions {
status: {
danger: React.CSSProperties['color']
}
}
}
declare module "@material-ui/core/styles/createPalette" {
interface Palette {
neutral: Palette['primary'];
}
interface PaletteOptions {
neutral: PaletteOptions['primary'];
}
}
<ThemeProvider theme={theme}>
<Button color="neutral" variant="contained">
neutral
</Button>
</ThemeProvider>
Picking colors
Ищите вдохновение? The Material Design team has built an palette configuration tool to help you.
Темный режим
Material-UI comes with two palette modes: light (the default) and dark. Вы можете сделать тему темной, установив режим mode: 'dark'
.
const darkTheme = createTheme({
palette: {
mode: 'dark',
},
});
While it's only a single value change, the createTheme
helper modifies several palette values. The colors modified by the palette mode are the following:
Typography
palette.text.primary
#fff
palette.text.secondary
rgba(255, 255, 255, 0.7)
palette.text.disabled
rgba(255, 255, 255, 0.5)
Buttons
palette.action.active
#fff
palette.action.hover
rgba(255, 255, 255, 0.08)
palette.action.selected
rgba(255, 255, 255, 0.16)
palette.action.disabled
rgba(255, 255, 255, 0.3)
palette.action.disabledBackground
rgba(255, 255, 255, 0.12)
Background
palette.background.default
#121212
palette.background.paper
#121212
Divider
palette.divider
rgba(255, 255, 255, 0.12)
Typography
palette.text.primary
rgba(0, 0, 0, 0.87)
palette.text.secondary
rgba(0, 0, 0, 0.6)
palette.text.disabled
rgba(0, 0, 0, 0.38)
Buttons
palette.action.active
rgba(0, 0, 0, 0.54)
palette.action.hover
rgba(0, 0, 0, 0.04)
palette.action.selected
rgba(0, 0, 0, 0.08)
palette.action.disabled
rgba(0, 0, 0, 0.26)
palette.action.disabledBackground
rgba(0, 0, 0, 0.12)
Background
palette.background.default
#fff
palette.background.paper
#fff
Divider
palette.divider
rgba(0, 0, 0, 0.12)
System preference
Пользователи могли указать предпочтение светлой или темной теме. The method by which the user expresses their preference can vary. It might be a system-wide setting exposed by the Operating System, or a setting controlled by the User Agent.
You can leverage this preference dynamically with the useMediaQuery hook and the prefers-color-scheme media query.
Например, можно включить темный режим автоматически:
import * as React from 'react';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { createTheme, ThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
function App() {
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const theme = React.useMemo(
() =>
createTheme({
palette: {
mode: prefersDarkMode ? 'dark' : 'light',
},
}),
[prefersDarkMode],
);
return (
<ThemeProvider theme={theme}>
<CssBaseline/>
<Routes />
</ThemeProvider>
);
}