liveBook · Manning

Auto-fit

As explained in CSS in Depth, Second Edition

Auto-fill and auto-fit are CSS Grid track-repetition keywords that determine how many tracks are generated to fit available space.

auto-fit is a CSS Grid track-repetition keyword used with repeat() to let the grid determine how many columns fit the available width. A common pattern is repeat(auto-fit, minmax(300px, 1fr)): each column stays at least 300px wide, while the tracks expand to use the container. section 17.2.1

Choose auto-fit when the grid should respond to both viewport size and the number of items:

  • Use auto-fit for responsive cards that should stretch across the available container width. section 17.2.1
  • Use minmax() to set a lower bound for each track while allowing remaining space to distribute through 1fr. section 5.4
  • Prefer auto-fit over auto-fill when unused tracks should not leave empty grid columns; non-empty tracks stretch instead. section 5.4
  • Use a simpler stacked layout at small widths, then enable the grid at a larger breakpoint when the design requires it. section 17.2.1

Responsive card grid

A card container can switch from stacked blocks to an adaptive grid: .flyin-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 2em; }. At narrower widths, fewer columns fit; at wider widths, more columns fit, while the cards remain equal-width tracks. section 17.2.1

Listing 17.6 Applying a grid layout
.flyin-grid {
  margin-inline: 1rem;
}

@media (min-width: 30em) {
  .flyin-grid {
    margin-inline: 5rem;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));     #1
    gap: 2em;
  }
}

Inspect the complete grid declaration and its breakpoint context for a practical auto-fit card layout. section 17.2.1

How CSS in Depth, Second Edition covers it

How deep it goes
Explains repeat(), minmax(), flexible track sizing, empty-track behavior, and breakpoint use without detailing browser layout internals.
Examples
Demonstrates portfolio photographs and chicken cards arranged in adaptive grids.
What it assumes
Assumes basic CSS Grid knowledge while demonstrating repeat(), minmax(), flexible tracks, and responsive breakpoints.
What you can do after
Apply it via CSS Grid to build adaptive columns without manually specifying each viewport’s column count.
How it connects
Links CSS Grid with repeat(), minmax(), implicit grid placement, flexbox, media queries, and responsive layout.

Also explained in

Compare how 2 books explain auto-fit →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.