mui / mui/material-ui

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

Open
#42,893 8 comments 1 reaction 1 assignee View on GitHub

@siriwatknp is already working on this.

Since Jul 10, 2024.

customization: theme docs scope: all components
Dominant language
JavaScript
Stars
99.1k
Forks
32.5k
Avg merge
2d 17h
Merged PRs (30d)
106

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.