material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

[material-ui][theme] Lower CSS Specificity for color scheme rules in CSS Vars Theme

Open joebochill opened this issue 7 months ago • 4 comments

Summary

I'm in the process of migrating themes to the new CSS Vars Theme/Provider. I have a light/dark theme which I'm combining per the migration guide into a single theme with dark/light color schemes.

As mentioned in the docs, this is causing a pretty big headache with regards to CSS rule specificity (any of the rules I set for the dark theme cannot be overridden in a component's sx prop without also specifying the color scheme selector.

I'm wondering if there is a better way that I should approach this or if there's a way that color schemes could be implemented without the extra css specificity.

Examples

This is a super simple example (not exactly what I'm doing in my theme, but shows the issue):

Let's say we have a rule in the theme for Button to change the background color:

styleOverrides: {
    root: ({ theme }) => ({
      backgroundColor: 'primary.main',
      [theme.getColorSchemeSelector('dark')]:{
          backgroundColor: 'primary.light'
      }
    }),
}

If I want to override the button background color somewhere in my project:

<Button sx={{backgroundColor: 'red'}} />

it only works for the light theme (with the old ThemeProvider approach, this would work for both).

To get it to work for the dark theme, I have to add an extra rule, which is a bit clunky:

<Button sx={(theme) => ({
    backgroundColor: 'red',
    [theme.getColorSchemeSelector('dark')]:{
        backgroundColor: 'red',
    }
})} />

Motivation

Essentially, I just want it to be easy to override theme styles for a component via sx without having to write a rule for both/all color schemes that I may have.

Search keywords: CssVars Theme getColorSchemeSelector specificity override sx

joebochill avatar Jul 10 '24 02:07 joebochill