Reputation: 17269
I have a responsive grid with:
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
grid-gap: 10px 10px;
How can I set the max number of columns to be four, while maintaining responsivity? That is, when the page is resized, the rows should collapse into one column as in the example, but have a max size of four columns.
So,
repeat(4, 1fr);
will not work.
Do I have to use flexbox? I've seen related answers on SO but none seem to explain it clearly.
Working example here.
Upvotes: 2
Views: 2479
Reputation: 125651
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>
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;
Upvotes: 3
Reputation: 4381
Isn't that You want to limit the maximum width of the grid, so the columns will fit based on that?
If the column is in minimal size of 100px
, then the max-width of grid can be set to 430px
(considering also the gaps on side):
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
grid-gap: 10px 10px;
max-width: 430px;
`;
To fit full screen, You can just raise the limits of minimal value to be /4
of grid width.
Upvotes: 0