Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
physicsboy Avatar asked Oct 31 '25 23:10

physicsboy


1 Answers

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

like image 106
Steve Gomez Avatar answered Nov 03 '25 13:11

Steve Gomez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!