You can use repeat()
, auto-fit
, and minmax()
to create a responsive grid that will fit as many items on a row as possible, while adhering to a minimum width per item. This is great for grids of cards. I usually use a number that is around 300px, as that's the minimum width of most small mobile devices when held in portrait mode.
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
Setting the max size to 1fr
will allow the grid items to expand to fill the available space. You can also set a max size, like minmax(300px, 400px)
, but you may get white space at the end of your rows.