Search code examples
cssmaterial-uicss-grid

Proper way to set margin between MUI grid items


I am trying to get some margin between my three grid items. I would like each grid item to take up 1/3 of the container's width. However, neither spacing nor gap prop is helping me to achieve this.

Using spacing
It seems like spacing only adds padding to each box. And padding is only added to the left and top.

<Grid container spacing={5} sx={{ width: 800, border: 1 }}>
  <Grid item xs={4} sx={{ backgroundColor: "yellow" }}>
    <div>Box 1</div>
  </Grid>
  <Grid item xs={4} sx={{ backgroundColor: "lightBlue" }}>
    <div>Box 2</div>
  </Grid>
  <Grid item xs={4} sx={{ backgroundColor: "limeGreen" }}>
    <div>Box 3</div>
  </Grid>
</Grid>

enter image description here

Using gap
gap creates margin between the grid items but pushes the third box out of the first row.

<Grid container gap={5} sx={{ width: 800, border: 1 }}>
  <Grid item xs={4} sx={{ backgroundColor: "yellow" }}>
    <div>Box 1</div>
  </Grid>
  <Grid item xs={4} sx={{ backgroundColor: "lightBlue" }}>
    <div>Box 2</div>
  </Grid>
  <Grid item xs={4} sx={{ backgroundColor: "limeGreen" }}>
    <div>Box 3</div>
  </Grid>
</Grid>

enter image description here

How can I achieve something like this? enter image description here

I generated this image by setting each grid item to take up 3 columns instead of 4 (see below). However, it feels hacky. Is there a better solution? I am also open to solutions that don't involve MUI grids.

<Grid
  container
  justifyContent="space-between"
  sx={{ width: 800, border: 1 }}
>
  <Grid item xs={3} sx={{ backgroundColor: "yellow" }}>
    <div>Box 1</div>
  </Grid>
  <Grid item xs={3} sx={{ backgroundColor: "lightBlue" }}>
    <div>Box 2</div>
  </Grid>
  <Grid item xs={3} sx={{ backgroundColor: "limeGreen" }}>
    <div>Box 3</div>
  </Grid>
</Grid>

Solution

  • To achieve a result like the image, I would suggest to give the background-color in the div inside the Grid item and use the padding for making it to have some white area on the right (if you don't want to use the spacing as it gives space around the Grid item)

      <Grid 
      container sx={{ width: 800, border: 1 }} m={2} 
      // spacing={2} decide if you want extra spacing or not
      >
        <Grid item xs={4}>
          <div style={{ marginRight: "40px", backgroundColor: "yellow" }}>
            Box 1
          </div>
        </Grid>
        <Grid item xs={4}>
          <div style={{ marginRight: "40px", backgroundColor: "lightblue" }}>
            Box 2
          </div>
        </Grid>
        <Grid item xs={4}>
          <div style={{ marginRight: "40px", backgroundColor: "limegreen" }}>
            Box 3
          </div>
        </Grid>
      </Grid>
    

    Here is a codesandbox