CSS has math and comparison functions like min(), max(), and minmax(). You have probably seen the issue that 3 columns layout looks strange at some viewport sizes where there isn’t enough room for content.
Let’s try to automate our grid layout with the magic of CSS:
.grid-auto-wrapper {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 22rem), 1fr));
grid-gap: 2rem;
}
This CSS creates a grid layout with a dynamic number of columns that adjust to the available space.
Let’s break down the most importan part of the CSS:
minmax(min(100%, 22rem), 1fr)
22 * 16px = 352px
screen.So, in summary, minmax(min(100%, 22rem), 1fr)
sets a minimum width for an element of 22rem or 100% of the container’s width (whichever is smaller) and allows the element to expand to fill any remaining space in the container.
22rem is kind of a magic number. That number with container width defines how many maximum columns we can have.
Check more details from demo of auto grid.