Alexander Schoch
Alexander Schoch

Reputation: 275

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

Upvotes: 4

Views: 1790

Answers (3)

mastra90
mastra90

Reputation: 1

Using marginRight or margin: auto isn't great. It seems that 100% of the width of the child cannot be used when using the spacing prop as it adds the spacing on the right side. I resolved this with flex:1 which allows you to use the spacing prop while also getting 100% of the width.

<Masonry columns={1} sx={{ flex: 1 }}>

Upvotes: 0

Az.Youness
Az.Youness

Reputation: 2652

I fix it simply by changing Masonry component width from "100%" to "auto", I don't know why, but it works great.

<Masonry columns={4} spacing={4} sx={{ width: "auto" }}>
  {* Masonry items *}
</Masonry>

Upvotes: 14

kausko
kausko

Reputation: 988

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>

Upvotes: 6

Related Questions