2

I have the following CSS:

@media screen and (min-width: 0px) and (max-width: 400px) {
    body { background-color: red; }
}
@media screen and (min-width: 401px) and (max-width: 599px) {
    body { background-color: blue; }
}
@media screen and (min-width: 600px) {
    body { background-color: green; }
}

And I have the following Material UI theme:

export const theme = createMuiTheme({
    palette: {
      background: {
        default: 'red'
      },
    }
});

I would like to replace the hard-coded CSS with breakpoints in the Material UI theme but I can't figure out how to do it. I've tried the following (and several variations) and nothing seems to work.

const defaultTheme = createMuiTheme();
export const theme = createMuiTheme({
    palette: {
      background: {
        [defaultTheme.breakpoints.down('sm')]: {
            default: 'red'
        }
      },
    }
});

Is this not supported by Material UI?

user2719094
  • 1,611
  • 5
  • 26
  • 36

1 Answers1

0

You can see here how theme.palette.background.default is leveraged. The syntax you tried will just add a new property to theme.palette.background that Material-UI will never look at.

What you can do is create some custom entries in your theme such as the following:

const theme = createMuiTheme({
  palette: {
    background: {
      xs: "red",
      sm: "blue",
      md: "green"
    }
  }
});

and then use this in styles:

const styles = theme => ({
  "@global": {
    body: {
      [theme.breakpoints.up("md")]: {
        backgroundColor: theme.palette.background.md
      },
      [theme.breakpoints.down("sm")]: {
        backgroundColor: theme.palette.background.sm
      },
      [theme.breakpoints.down("xs")]: {
        backgroundColor: theme.palette.background.xs
      }
    }
  }
});

Edit CssBaseline overrides

Slightly related question: Using createMuiTheme to override default styles on div's, p's, body

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198