Grid layout without media queries

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)
  • min() function picks the smaller value out of 22rem and 100%. This is important so that our column does not overflow in small screens creating horizontal scrollbar. In here our small screen means smaller than 22 * 16px = 352px screen.
  • In minmax() function minimum is either 22rem or 100% as defined above.
  • The maximum size is set to 1fr, which means that the element will expand to take up any remaining space in the container after the minimum size is accounted for.

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.

More reading