javascriptcssreactjsmaterial-uibreakpoints

Mui sx styling ONLY at certain breakpoint


I am converting some old mui styling to use the sx attribute and have seen that you can specify styles as different breakpoints with sx = {{ someCssProp: { xs: ..., md: ... etc.

I have previously been using theme.breakpoints.only for some of my stylings and after reading the official docs on breakpoint usage, it sounds like the xs, md, ... usage within sx will only apply theme.breakpoints.up... meaning that if I want styling only at xs, doing something like:

<Box sx={{background: {xs: 'blue'}}}>Some content</Box>

Will mean that the Box has a blue background from xs...

Is there a way in which I can replicate my .only use case?


Solution

  • As you've noticed, the breakpoints object syntax only applies going "up" (larger) per the docs:

    Breakpoints as an object

    The first option for breakpoints is to define them as an object, using the breakpoint values as keys. Note that each property for a given breakpoint also applies to all larger breakpoints in the set. For example, width: { lg: 100 } is equivalent to theme.breakpoints.up('lg').

    That does mean that with your current code the Box has a blue background from xs up.

    Since you're trying to define styles for only one particular breakpoint, you will need to define your own behavior, using the theme breakpoints helper functions, in the sx prop. For example:

    <Box
      sx={(theme) => ({
        [theme.breakpoints.only("sm")]: {
          backgroundColor: 'blue'
        }
      })}
    >
      Some content
    </Box>
    

    Working CodeSandbox: https://codesandbox.io/s/mui-breakpoints-in-sx-only-yr7h42?file=/demo.tsx