Skip to content
+

CSS theme variables - Native color

Learn how to use native color with CSS theme variables.

Benefits

  • No need to use JavaScript to manipulate colors.
  • Supports modern color spaces such as oklch, oklab, and display-p3.
  • Supports color aliases to external CSS variables.
  • Automatically calculates contrast text from the main color.

Usage

Set cssVariables with nativeColor: true in the theme options. Material UI will start using CSS color-mix and relative color instead of the JavaScript color manipulation.

const theme = createTheme({
  cssVariables: {
    nativeColor: true,
  },
});

Modern color spaces

The theme palette supports all modern color spaces, including oklch, oklab, and display-p3.

const theme = createTheme({
  cssVariables: { nativeColor: true },
  palette: {
    primary: {
      main: 'color(display-p3 0.5 0.8 0.2)',
    },
  },
});

Aliasing color variables

If you're using CSS variables to define colors, you can provide the values to the theme palette options.

const theme = createTheme({
  cssVariables: {
    nativeColor: true,
  },
  palette: {
    primary: {
      main: 'var(--colors-brand-primary)',
    },
  },
});
Press Enter to start editing

Theme color functions

The theme object contains these color utilities: alpha(), lighten(), and darken().

When native color is enabled, these functions use CSS color-mix() and relative color instead of the JavaScript color manipulation.

theme.alpha(color, 0.5)
oklch(from #2196f3 l c h / 0.5)
theme.lighten(color, 0.5)
color-mix(in oklch, #2196f3, #fff 50%)
theme.darken(color, 0.5)
color-mix(in oklch, #2196f3, #000 50%)

Contrast color function

The theme.palette.getContrastText() function produces the contrast color. The demo below shows the result of the theme.palette.getContrastText() function, which produces the text color based on the selected background.

Caveats

  • Because of the differences in how contrast is calculated between CSS and JavaScript, the resulting CSS colors may not exactly match the corresponding JavaScript colors to be replaced.
  • In the future, the relative color contrast will be replaced by the native CSS contrast-color() function when browser support is improved.
  • For relative color contrast, the color space is automatically set to oklch internally. Currently it's not possible to change this, but please open an issue if you have a use case that calls for it.