How can I set the max number of columns to be four, while maintaining
responsivity?
As hinted by @Powell_v2 in the comments - You will need to set a media query to modify the value for the grid-template-columns property when the maximum number of columns are reached.
Using the OP's example, on narrow viewport widths (where we have less than the maximum number of columns) we want responsive columns - so we can use the OP's code for the grid-template-columns property:
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr))
However, when we reach the maximum number of columns we want the grid to stop being responsive - at this point a media query should kick in to modify the value for grid-template-columns.
We can calculate this break-point - assuming the grid takes up the whole viewport - as follows:
max number of cols * min column width + (max number of cols -1) * column gap
So here it will be: 400px + 30px = 430px
At this point - we don't want additional columns - we just want the columns to be the same width.
@media (min-width: 430px) {
.wpr {
grid-template-columns: repeat(4, 1fr);
}
}
So the solution will look something like this:
body {
margin: 0;
}
.wpr {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
grid-gap: 10px 10px;
}
.wpr > div {
border: 5px solid green;
min-height: 50px;
}
@media (min-width: 430px) {
.wpr {
grid-template-columns: repeat(4, 1fr);
}
}
<div class="wpr">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
Codepen Demo (Resize to see the effect)
NB: We can take advantage of a preprocessor such as SASS to achieve a more general and reusable solution:
// Set custom values for 1) Minimum Column width 2) Maximum # columns 3) Gap size
$min-col-width: 150;
$max-cols: 5;
$gap-size: 30;
$break-point: $min-col-width * $max-cols + $gap-size * ($max-cols - 1) * 1px;
auto-fit->4, during resize the cols change size properly. But they are always in the row.