Philip Claren
Philip Claren

Reputation: 2886

In material-ui, how can I set different theme-styles for different breakpoints?

This questions targets material-ui 1.0.

When I create a theme with createMuiTheme, how can I set, for example for typography.title, different styles for different breakpoints? On a component level I can achieve this with something like this:

const styles = theme => ({
  title: {
    fontSize: 34,
  },
  [theme.breakpoints.down('sm')]: {
    title: {
      fontSize: 28,
    }
  },
})

Upvotes: 1

Views: 1907

Answers (2)

Ricardo Canelas
Ricardo Canelas

Reputation: 2460

There is another way to work with createMuiTheme with the breakpoints methods.

If you check the createMuiTheme core, you will see that it uses the createBreakpoints class.

So, you can do like that:

// theme.js

import createBreakpoints from '@material-ui/core/styles/createBreakpoints'
import { createMuiTheme } from '@material-ui/core/styles'

const breakpoints = createBreakpoints({})

const theme = createMuiTheme({
  overrides: {
    MuiTab: {
      root: {
        [breakpoints.up('lg')]: {
          minWidth: '200px',
          backgroundColor: 'yellow',
        },
      },
      wrapper: {
        padding: '0 10px',
        backgroundColor: 'black',
      },
    },
  },
})

export default theme

(tested: @material-ui/core 4.0.1)

Upvotes: 2

Rikku
Rikku

Reputation: 438

Material-ui sure has a lot of different theming solutions. When you look for one that would be useful to you, you are looking for two things:

  1. Creating a theme that can be applied to component hierarchy.

Doc page "Nesting the theme"

  1. Changing single styling rules while keeping the others intact.

Doc page "Customizing all instances of component type" and "Typography API"

The key to make it work is to create a second theme that can see the breakpoints, and provide it with some special options for overriding typography:

...outerTheme,
overrides: {
  MuiTypography: {
    title: {
      [outerTheme.breakpoints.down("sm")]: {
        fontSize: 28
      },
    }
  }
}

I find the "Nesting the theme" example code suitable to test it on, so this is what it could look like: codesandbox.io/s/98192p85zy

EDIT: replaced the final code link to make it more useful an answer than just the examples from the docs.

Upvotes: 2

Related Questions