Search code examples
material-uigridspacingbox

mui Grid in Box - horizontal and vertical spacing


I want to make a grid of many cards with the same horizontal and vertical spacing. See below my code. I want to keep the different Box elements because other codes will be added. I tried to play with the flexbox options of the mui Box but nothing worked.

import * as React from 'react';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';


const list_label = [
  'T1 ',
  'T2 ',
  'T3 ',
  'T4 ',
  'T5 ',
  'T6 ',
  'T7 ',
  'T8 ',
  'T9 ',
  'T10 ',
  'T11 ',
  'T12 ',
  'T13 ',
];

export default function TestBasicGrid() {
  return (
    <Box sx={{
      display: 'flex',
      flexDirection: 'row',
      height:800,
      width:'100%',
      flexGrow: 1,
      alignContent:'flex-start'
    }}>
      <Box sx={{
        display: 'flex',
        flexDirection: 'row',
        height:'100%',
        width:'100%',
        alignContent:'flex-start'
      }}>
        <Box sx={{
                display: 'flex',
                flexDirection: 'column',
                border:'3px solid black',
                width:'100%',
                height:'100%',
                alignContent:'flex-start'
              }}>
          <Box
          sx={{ height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  border:'3px solid green',
                  padding: 2,
                  paddingTop:10,
                  paddingLeft:10,
                  paddingBottom:10,
                  alignContent:'flex-start'

              }}>
            <Grid container
                  rowSpacing={2}
                  columnSpacing={2}
                  justifyContent='flex-start'
                  alignItems='flex-start' 
                  sx={{ flexGrow: 1,
                        overflowY: '"scroll',
                    }}>
              {list_label.map((label) => (
                <Grid item key={label}>
                  <Paper sx={{
                      height: 120,
                      width: 150,
                      backgroundColor: 'red'}}>{label}</Paper>
                </Grid>
              ))}
            </Grid>
          </Box>
        </Box>
      </Box>
      </Box>
  );
}

The result show different horizontal and vertical spacing.

result


Solution

  • Remove the flexGrow: 1 from the <Grid> conatiner

    <Grid 
      container
      rowSpacing={2}
      columnSpacing={2}
      justifyContent='flex-start'
      alignItems='flex-start'
      // --- remove this flexGrow --- //
      sx={{ flexGrow: 1, overflowY: 'scroll' }}
    >
      {list_label.map((label) => (
        <Grid item key={label}>
          <Paper sx={{ height: 120, width: 150, backgroundColor: 'red'}}>
            {label}
          </Paper>
        </Grid>
      ))}
    </Grid>