简体   繁体   中英

Padding breakpoints in MUI5 sx props

I'm refactoring some components to use the latest MUI version.
As so, I'm often "translating" old classes into the sx props and I found myself enjoying this new way of styling which is more readable imho.

One thing aches me though, I couldn't find how to handle breakpoints in the sx props while still leveraging the theme.spacing() mapping.

I had this basic class that was styling a div with some padding :

// old class
titleContainer: {
    display: "flex",
    alignItems: "center",
    [breakpoints.up("lg")]: { padding: spacing(3, 5, 2) },
    [breakpoints.down("lg")]: { padding: spacing(2, 2, 1) },
    [breakpoints.down("sm")]: { padding: spacing(2, 1, 1) },
  },

Now I have this Box :

<Box
  display="flex"
  alignItems="center"
  sx={{
    padding: {
      xs: theme.spacing(2, 1, 1),
      md: theme.spacing(2, 2, 1),
      lg: theme.spacing(3, 5, 2),
      },
  }}
>

This works fine, but with the latest MUI update we often don't need to use theme.spacing() anymore, and this array notation would work as well :

sx={{ p: 2 }} OR sx={{ p: [2,1] }}

But the same notation is not recognize when used for a breakpoints which I don't get, and that forces me to either use strings (and computed px values) or theme.spacing() .

It's not that important, but I'd like to understand why and how can I improve this.

Cheers!


EDIT
I just realized that having p: [2, 1] doesn't translate to padding: 16px 8px; as I initially thought. The array is a shorthand to breakpoints : p: [2, 1] == p: {xs: 2, sm: 1}

While that clears things up a little bit, I'm still unsure about the "cleanest" way to define a more complex padding with breakpoints. From what I understand it would be something like :

sx:{{
  pt: [2,1],
  px: 2,
  pb: [2,3],
}}

you need to add the breakpoints inside the css property. for different padding at different sides you need to use proper css property like p, pl, pr, pt, pb, px, py for all supported css properties in sx props please check https://mui.com/system/properties/

sx={{ 
  p: { xs: 2, md: 4, lg: 6 }, // for all sides
  px: { xs: 2, md: 4, lg: 6 }, // for left and right side
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM