Responsive auto-fill and auto-fit
Definition and purpose
Automatic repetition makes a grid adapt its column count to available width. Auto-fill reserves as many repeated tracks as fit; auto-fit collapses empty repeated tracks after placement, allowing occupied flexible tracks to expand.
Keep empty column
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: grid; grid-template-columns: repeat(auto-fill, minmax(90px, 1fr)); gap: 15px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>Three 90px tracks fit; the third is empty but reserved.
Syntax and mental model
repeat(auto-fit, minmax(90px, 1fr)) combines a minimum with flexible growth. With a definite 300px width and 10px gaps, three 90px minimum tracks fit. If only two items exist, auto-fit collapses the unused track and its adjacent gutters; auto-fill retains it.
Collapse empty column
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: grid; grid-template-columns: repeat(auto-fit, minmax(90px, 1fr)); gap: 20px; width: 340px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>Three minimum tracks fit, but only two remain occupied and expand to 160px.
Common mistakes
A fixed minimum can overflow a container narrower than that minimum. Consider a smaller responsive minimum (for example min(100%, 90px)) and test actual content. Do not expect auto-fit to differ from auto-fill when all repeated tracks are occupied.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Implicit tracks and auto-placement. Next lesson: Grid alignment and subgrid.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Responsive auto-fill and auto-fit — knowledge check
Five questions on responsive auto-fill and auto-fit.
Which keyword retains empty repeated tracks?
Which collapses empty repeated tracks after placement?
With two occupied flexible tracks in 300px and a 10px gap, what is each width if minima allow?
When can a fixed minimum overflow?
When can auto-fill and auto-fit produce the same layout?