Nesting MUI grid inside stack with spacing

Viewed 152

Nesting an MUI Grid (container) inside an MUI Stack (with spacing applied) causes issues with margin styles. Since the Stack automatically "voids" all margin applied to its children (to allow for its own spacing margin), and the Grid container requires negative margin to layout properly, using the two together results in shifted layouts (mainly horizontally). Is there a nice way to get around this, other than having to avoid using a Stack parent with spacing, and applying said spacing manually to all children? This seems like a relatively common use case, and I was hoping to find a way to disable the Stack from "voiding" its child item's margins?


This does not work, because the parent Stack "voids" the child grid's negative margin, in order to apply its own spacing margin (only vertical).

<Stack spacing={2}>
  <Grid container spacing={3}>
    <Grid item>...</Grid>
  </Grid>
  <Grid container>...</Grid>
  <WhateverElse />
</Stack>
.css-1lwbda4-MuiStack-root>:not(style)+:not(style){
  margin:0;margin-top:24px;
}

This works, because the parent Stack does not specify spacing, which allows children to keep their margins (negative margins in case of Grid).

<Stack>
  <Grid container spacing={3}>
    <Grid item>...</Grid>
  </Grid>
  <Grid container>...</Grid>
  <WhateverElse />
</Stack>```
0 Answers
Related