AZ.dev

Responsive grid columns with auto-fit or auto-fill

| browsers: all modern

Use auto-fit for a row of cards that should fill the width. Use auto-fill when a short row should keep its columns at their minimum size instead of stretching.

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1rem;
}

Both create as many 240px-minimum columns as fit, and both wrap items onto new rows as the container narrows, with no media query.

The one difference

They diverge only when there are fewer items than columns. Say the container fits four columns and there are two items:

Cards, tiles, image galleries: auto-fit, so a single result doesn’t sit in a narrow column. Form fields or a toolbar where one control shouldn’t balloon: auto-fill.

Gotchas

grid auto-fit auto-fill responsive minmax

This entry is one card on a printable cheat sheet:

CSS & Layout Essentials Cheat Sheet

Was this helpful?

Related Entries

Stop a flex or grid child from overflowing its containerWhy position sticky isn't sticking