Back
Modern CSS Grid
July 2023
CSS
Responsive
Modern CSS Grid has made implementing highly responsive page behaviour far easier. By using a combination of auto-fit and minmax for the grid-template-rows property, we can dynamically set the number of columns that a grid should have based on the available width.
We're basically saying - "fit as many columns as possible that have a minimum width of X, and make them stretch to fill all the available space". The behaviour can be seen more easily when resizing the page - when shrinking the screen, if we run out of space (ie. if the columns width hit the defined minimum width), then remove a column from the grid. When expanding the screen - if we reach the point where we have enough space for another column and all columns would still have a width above the mininum width that we specified, then add another column.
We can count on CSS to automatically place implicit grid children for us - ie. if we need grid items to reflow to a new row, it'll handle that automatically for us.
Resize the window to see the example in action:
3 simple lines of CSS code:
display: flex;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-gap: 24px;