Flexbox can do this easily.
- You should create 2 variables for the amounts of columns and one for the gap. That going to make the rest easier to adjust and maintain later on.
- Instead of grid use
display: flex
- To allow a break to the next row after a certain amount of elements you can use the
flex-wrap: wrap
property. - To center the child elements within that “grid” you can use
justify-content: center
which will center the elements along the main axis. - Now the hard part is to calculate the correct width of the grid cards. For that, you can use the
calc
-function. The entire width is100%
from here we need to start. Then we need to subtract the gaps. The amount of gaps iscolumns - 1
. Then we multiply the number of gaps by the gap size:(amount of gaps - 1) * gap size
. That value we subtract as said from the 100% width:100% - ((amount of gaps - 1) * gap size)
. Last but not least we divide that sum by the number of columns:
:root {
--grid-columns: 3;
--grid-gap: 5px;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: var(--grid-gap);
}
.container > * {
width: calc((100% - (var(--grid-gap) * (var(--grid-columns) - 1))) / var(--grid-columns));
}
span {
border: 1px solid black;
box-sizing: border-box;
}
<div class="container">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
</div>