I have this simple grid:
.outGrid {
display: grid;
grid-gap: 40px;
grid-template-columns: repeat(3, 1fr);
}
.item {
width: 40px;
height: 40px;
background-color: grey;
}
<div class='outGrid'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
As you can see, I've defined the grid-gap to be 40px, but each grid item stretches horizontally as page width changes. I'd like the item to not stretch and simply occupy full space, so both vertical and horizontal gaps are 40px to form a nice 3*3 grid. How to achieve that?
Use auto instead of 1fr and align the content:
.outGrid {
display: grid;
grid-gap: 40px;
grid-template-columns: repeat(3, auto);
place-content: start;
}
.item {
width: 40px;
height: 40px;
background-color: grey;
}
<div class='outGrid'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
How to stop grid item from stretching?
The grid items are not stretching. They are exactly what you defined them to be:
.item {
width: 40px;
height: 40px;
background-color: grey;
}
What's actually stretching are the grid columns, which you defined to consume all available space:
.outGrid {
display: grid;
grid-gap: 40px;
grid-template-columns: repeat(3, 1fr); <-- fr units consume available space
}
Here's how the browser sees it:

You can see each column taking an equal portion of the row.
You can see the 40px grid gaps.
You can see that the grid items are placed at the start of each cell.
One simple and easy way to create the "nice 3x3 grid" that you want is to switch the dimensions from the grid items to the grid container:
.outGrid {
display: grid;
grid-gap: 40px;
grid-template-columns: repeat(3, 40px);
grid-auto-rows: 40px;
}
.item {
background-color: grey;
}
<div class='outGrid'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With