javascriptreactjsmaterial-uimasonry

Material-UI Masonry: Remove space on right side


Using Material-UI, the width of the Masonry Component doesn't fill the width of the parent container. The width of this missing space is exactly the width of the spacing, which makes sense if there's an element next to it.

I tried to calculate the width of the masonry to be the width of the Box element plus 8 * spacing, but this breaks as soon as there is a scrollbar involved.

How can I use the full width of the container for Masonry?

mwe (just an example from the documentation with a Box added on top):


const heights = [150, 30, 90, 70, 110, 150, 130, 80, 50, 90, 100, 150, 30, 50, 80];

const Item = styled(Paper)(({ theme }) => ({
    ...theme.typography.body2,
    color: theme.palette.text.secondary,
    border: '1px solid black',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
}));

<Container>
    <Box style={{ border: '1px solid black', padding: '20px' }}>
        <Typography variant="h5">
          An Element to show the width of the contianer
        </Typography>
    </Box>

    <Box style={{ marginTop: '20px' }}>
        <Masonry columns={4} spacing={4}>
          {heights.map((height, index) => (
            <Item key={index} sx={{ height }}>
              {index + 1}
            </Item>
          ))}
        </Masonry>
    </Box>
</Container>

Screenshot of the MWE. Missing Area marked in red:

Screenshot of the MWE. Missing Area marked in red


Solution

  • You can fix this by setting marginRight with the negation of your masonry spacing in the sx prop.

    <Box sx={{ marginTop: '20px', marginRight: -4 }}>
       {/* Masonry code */}
    </Box>