I have a css grid. It contains a dynamic number of elements. Something like this:
<Box className={classes.Grid}>
<Button variant="outlined">1</Button>
<Button variant="outlined">2</Button>
<Button variant="outlined">3</Button>
<Button variant="outlined">4</Button>
<Button variant="outlined">5</Button>
<Button variant="outlined">6</Button>
<Button variant="outlined">7</Button>
<Button variant="outlined">8</Button>
<Button variant="outlined">9</Button>
<Button variant="outlined">10</Button>
</Box>
And
const useStyles = makeStyles({
Grid: {
display: "grid",
gridTemplateColumns: "repeat(3, 1fr)",
gridGap: "10px",
margin: "auto",
width: "90vw",
}
});
So how can I make the nr of columns on each row dependent on the size of the grid element? Also forgot to mention that every child has a specific width/height (220px/200px)
CodePudding user response:
You are probably looking for auto-fill. It automatically fills the rows with as many elements which can fit in that row. Try
gridTemplateColumns: "repeat(auto-fill, 5em)"
You can adjust 5em to your needs.
You can combine that with the function minmax() to only define a minimum size for the buttons and let them stretch the last bit in order to fill the whole width and not only in n*button_width increments.
gridTemplateColumens: "repeat(auto-fill, minmax(5em, 1fr))"
Again, adjust 5em to the width your buttons need to have at the minimum.
Here is how that would look (in plain HTML):
.grid{
display: grid;
gap: 1em;
grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}
.grid > div{
width: 100%;
text-align: center;
background: grey;
}
<div >
<div>Element 1</div>
<div>Element 2</div>
<div>Element 3</div>
<div>Element 4</div>
<div>Element 5</div>
<div>Element 6</div>
<div>Element 7</div>
<div>Element 8</div>
<div>Element 9</div>
</div>
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns
CodePudding user response:
If you just want to have rows to fill the free space, then @robske_110's answer is what you want.
But if you want to have more control when and how much size to have, then I'd recommend making a use of breakpoints built in MUI.
Here is the sandbox link and example below.
const useStyles = makeStyles((theme) =>
createStyles({
Grid: {
display: "grid",
gridTemplateColumns: "repeat(3, 1fr)",
gridGap: "10px",
margin: "auto",
width: "90vw",
[theme.breakpoints.down("sm")]: {
gridTemplateColumns: "repeat(2, 1fr)"
}
}
})
);
