Define custom CSS variables in MUI for both light and dark mode

2 weeks ago 13
ARTICLE AD BOX

You can create these three files, starting with the index that also defines the types:

themeTypes.ts

export interface CustomPaletteExtensions { customVariable: string; } declare module '@mui/material/styles' { interface Palette extends CustomPaletteExtensions {} interface PaletteOptions extends Partial<CustomPaletteExtensions> {} }

Then a file for dark and another one for light, for example:

import { createTheme } from '@mui/material/styles'; import './themeTypes'; const lightTheme = createTheme({ palette: { mode: 'light', customVariable: '#fff' } } export default lightTheme;

and to apply them use it in the ThemeProvider:

<ThemeProvider theme={theme}> {children} </ThemeProvider>

"theme" is here a import from lightTheme or darkTheme

You can use like

styles={{ color: "customVariable" }}

Eduardo Grigull's user avatar

The final version I went with is a little different from the provided answer, but the decisive hint was to do the module augmentation with the Palette object:

export interface CustomPaletteExtensions { customBackground: string; } declare module '@mui/material/styles' { interface Palette extends CustomPaletteExtensions {} interface PaletteOptions extends Partial<CustomPaletteExtensions> {} } const theme = createTheme({ cssVariables: { cssVarPrefix: 'abc', colorSchemeSelector: 'class', }, colorSchemes: { dark: { palette: { customBackground: '#2e2f3b', }, }, light: { palette: { customBackground: '#ffffff', }, }, }, }); export const theme;

Now I can use it like this:

var(--abc-palette-customBackground)

user3629892's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article