Responsive Grid Tracks
The previous reading assignment covered placing items into named areas and along named lines. Those techniques assume you already know your layout structure: how many columns, how many rows, where things go. This reading assignment addresses a different scenario: what happens when you do not know how many columns you need because the content or the viewport will determine that at runtime? CSS Grid provides a set of tools specifically for this situation, and they produce responsive layouts with remarkably little code.
The repeat() Function
Before exploring automatic track creation, it helps to understand repeat(), the function that makes it concise. Instead of listing the same track size multiple times, you pass a count and a size:
/* Without repeat() */
grid-template-columns: 1fr 1fr 1fr 1fr;
/* With repeat() */
grid-template-columns: repeat(4, 1fr);
Both declarations produce four equal columns. The repeat() function accepts any valid track size as its second argument, including named lines, minmax() expressions, and keyword sizes. The first argument does not have to be a fixed number. That is where auto-fill and auto-fit come in.
auto-fill and auto-fit
When you replace the count in repeat() with auto-fill or auto-fit, the browser figures out how many tracks fit in the available space instead of you specifying a number. Both keywords produce the same number of columns when the grid has enough items to fill all the tracks. The difference only appears when there are fewer items than tracks.
How Each Keyword Behaves
With auto-fill, the browser creates as many tracks as will fit, even if some of those tracks are empty. The empty tracks still occupy space in the grid. With auto-fit, the browser creates tracks for the items that exist and then collapses any empty tracks to zero width, allowing the existing items to stretch and fill the available space.
In practical terms: use auto-fill when you want a consistent grid structure regardless of item count, and items should not stretch to fill gaps. Use auto-fit when you want items to expand and fill the row when there are not enough of them to naturally fill it.
See the Difference
The demo below shows the same three items in both an auto-fill grid and an auto-fit grid. Resize the container with the slider and watch how each grid responds when tracks cannot all be filled with items.
auto-fill: empty tracks hold spaceauto-fit: empty tracks collapseThe minmax() Function
On its own, auto-fill and auto-fit need a track size to work with. A fixed size like 150px works, but it means tracks never grow beyond that size. The minmax() function solves this by giving a track a minimum and a maximum size. The browser will make the track at least as wide as the minimum and at most as wide as the maximum:
This declaration tells the browser: create as many columns as fit in the available space, where each column is at least 200px wide and can grow up to an equal share of the remaining space. The result is a grid that adds and removes columns automatically as the container grows or shrinks, with items always stretching to fill the row cleanly.
The min() Safety Fix
There is a subtle problem with the pattern above. If the container is narrower than the minimum track size (200px in the example), the track will overflow rather than shrink. This happens most commonly in narrow columns, sidebars, or when a grid is nested inside a flex container that has not been given a width constraint.
The fix is to replace the fixed minimum with min(200px, 100%). The min() function returns whichever value is smaller: the fixed pixel value, or 100% of the available space. This means the track will never be wider than its container, even if that container is smaller than the minimum you intended:
/* Can overflow on narrow containers */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
/* Safe on any container width */
grid-template-columns: repeat(auto-fit, minmax(min(200px, 100%), 1fr));
min() Safety Pattern
Get into the habit of writing minmax(min(Xpx, 100%), 1fr) instead of minmax(Xpx, 1fr) for any auto-fill or auto-fit grid. The two declarations behave identically in most situations, but the safer version prevents a class of hard-to-debug overflow bugs that only appear in specific container configurations.
Choosing a Minimum Track Size
The minimum value in minmax() determines roughly how many columns appear at any given container width. A 200px minimum in a 900px container produces around four columns. A 300px minimum in the same container produces three. There is no single correct minimum; it depends on the content. Cards with images typically need at least 200 to 280px. Text-heavy tiles may need 300 to 400px. Data table columns may only need 80 to 120px. Set the minimum to the smallest width at which the content still looks reasonable, then let the grid handle everything else.
Intrinsic Track Sizing
In addition to fixed sizes and minmax(), CSS Grid supports intrinsic sizing keywords that let the content itself determine the track size. These keywords are less commonly used than auto-fill with minmax(), but they are powerful in specific scenarios.
min-content
A track sized with min-content is as narrow as it can be without causing overflow. For text, that is the width of the longest word or unbreakable run. For images, it is the intrinsic image width (unless constrained). A min-content column will be just wide enough to prevent line overflow, and no wider.
max-content
A track sized with max-content is as wide as it needs to be to display its content on a single line with no wrapping. For text, that means the entire paragraph becomes one long line. This is rarely appropriate for text content, but it is useful for columns that should never wrap, such as icon labels, timestamps, or short status badges.
fit-content()
The fit-content() function is a capped max-content. It sizes the track like max-content up to the limit you provide, then stops growing. This is useful when you want a column to size itself to its content but you need to prevent it from growing beyond a certain width:
The first column will be as wide as its content up to 300px. The second column takes the remaining space. If the content in the first column is only 120px wide, the second column gets more room. If the content would be 400px wide, the first column is capped at 300px and the content wraps.
When to Use Intrinsic Sizing
Intrinsic sizing keywords are most useful in two-column utility layouts where one column adapts to its content and the other fills the rest. A label-and-value pair, a sidebar navigation with variable-length items, or an image with a caption alongside it are all good candidates. For card grids and multi-column layouts where you want uniform columns, minmax() with auto-fit is almost always the better tool.
Filling Holes with Dense Packing
When some grid items span multiple columns or rows, the default placement algorithm can leave empty cells. Item 1 might span three columns in the first row, leaving a single-cell hole that later one-column items never fill, because the browser places each item in source order and refuses to move an item backward into an earlier hole.
Setting grid-auto-flow: dense changes that behavior. The browser still places items in source order first, but it then looks for earlier empty cells that later items could fill. The result is a tighter packing with fewer gaps. The tradeoff is that visual order can diverge from DOM order: item 3 might appear above item 2 on screen, which affects reading order and keyboard tab order. Prefer dense packing when filling holes matters more than keeping visual sequence identical to source order.
The demo below uses a four-column grid. Items 1 and 2 each span three columns, so sparse placement leaves a one-cell hole at the end of each of those rows. Items 3 through 8 are single cells. With dense packing off, those holes stay empty and the small items continue forward. Turn the switch on and watch items 3 and 4 jump backward to fill the holes. Watch the numbers: source order stays the same, but visual positions change.
Grid vs. Flexbox: A Decision Framework
CSS Grid and Flexbox both arrange items in a container, and both can produce layouts that look similar on screen. The practical question every developer faces is which one to reach for. The answer lies in whether your layout is primarily driven by the container or by the content.
Flexbox Is Content-Driven
Flexbox works outward from the items. Each item sizes itself based on its content (or an explicit size you provide), and the container accommodates them. Items can wrap to new rows, but each row is independent: items in row two have no relationship to items in row one. Flexbox is the right tool when you want items to be naturally sized and the layout to flow around them, such as navigation links, tag clouds, button groups, or any situation where the number and size of items varies and you want them to pack together naturally.
Grid Is Container-Driven
Grid works inward from the container. You define a structure of rows and columns, and items are placed into that structure. Items in the same column are aligned with each other across rows because they share the same track. Grid is the right tool when the layout structure matters independently of the content, such as page layouts, card grids, data tables, and any design where alignment across rows and columns is intentional and important.
The One-Sentence Rule
If you are thinking about the relationship between items in the same row or the same column, use Grid. If you are thinking only about the items themselves and how they flow, use Flexbox. A responsive card grid where all cards should align in both dimensions is a Grid problem. A header where a logo, navigation, and a button sit on one line and wrap gracefully on small screens is a Flexbox problem.
Grid and Flexbox are not competing technologies. It is common to use Grid for the overall page structure and Flexbox inside individual grid items to arrange their internal content. Neither one replaces the other.
Check Your Understanding
Write a Responsive Card Grid
A student just learned about auto-fill, auto-fit, minmax(), and the min() safety pattern in an Advanced CSS course. They understand that auto-fit collapses empty tracks, that minmax() gives tracks a minimum and maximum size, and that wrapping the minimum in min(Xpx, 100%) prevents overflow on narrow containers. They are writing a responsive card grid that should display as many columns as fit in the container, where each card is at least 240px wide, cards stretch to fill available space, and the grid never overflows its container. Review their code and give direct feedback. Check that they used auto-fit rather than auto-fill (since cards should fill the row), that minmax() is written correctly with the min() safety wrapper as the minimum value, that the maximum is 1fr, and that the gap is reasonable. Watch for using auto-fill when auto-fit is more appropriate, writing a fixed pixel minimum without the min() safety wrapper, and setting the maximum to a fixed size instead of 1fr. Guide them toward the specific concept they need to revisit rather than rewriting the code.
/**
* Write a responsive card grid where:
* - Columns are created automatically based on available space
* - Each card is at least 240px wide
* - Cards stretch to fill the row evenly
* - The grid never overflows its container
* - A comfortable gap separates the cards
*/
.card-grid {
display: grid;
/* Write the grid-template-columns rule here */
/* Add a gap */
}
Choose the Right Layout Tool
The same student is now practicing the decision between CSS Grid and Flexbox. They learned that Grid is container-driven and appropriate when alignment across rows and columns matters, and that Flexbox is content-driven and appropriate when items should size naturally and flow. They understand that both tools can be used together. They are given four layout scenarios and must identify which tool is most appropriate for each. Review their answers and give direct feedback. Check that they correctly identified Grid scenarios (card grids, page layouts, data tables, anything requiring two-dimensional alignment) and Flexbox scenarios (nav bars, button groups, tag lists, anything where items flow and wrap naturally). Watch for choosing Grid when content flow is the only concern, or choosing Flexbox when cross-row column alignment is needed. Guide them toward the one-sentence rule: if thinking about relationships between rows and columns, use Grid; if thinking only about items and their flow, use Flexbox.
/**
* For each scenario, write either "Grid" or "Flexbox" as a comment
* and a one-sentence reason why.
*
* Scenario 1: A photo gallery where all thumbnails should align
* in rows and columns regardless of count.
*
* Scenario 2: A site header containing a logo, a nav menu,
* and a login button that should wrap on small screens.
*
* Scenario 3: A pricing table where three plans sit side by side
* and every feature row aligns across all three columns.
*
* Scenario 4: A list of tags on a blog post that should wrap
* naturally and each tag should be only as wide as its text.
*/
/* Scenario 1: */
/* Scenario 2: */
/* Scenario 3: */
/* Scenario 4: */
Key Concepts Summary
The repeat() function accepts auto-fill or auto-fit as its count argument, letting the browser determine how many tracks fit in the available space. The two keywords behave identically when all tracks are occupied. When tracks are empty, auto-fill preserves those empty tracks and their space, while auto-fit collapses them so existing items can expand and fill the row.
The minmax() function gives a track a minimum and maximum size, and combining it with auto-fit produces the standard responsive card grid pattern. Wrapping the minimum value in min(Xpx, 100%) prevents overflow when the container is narrower than the intended minimum, and should be used by default. Intrinsic sizing keywords (min-content, max-content, fit-content()) let the content itself determine track width, and are most useful in two-column utility layouts rather than card grids. When spanning items leave empty cells, grid-auto-flow: dense backfills those holes with later items, at the cost of letting visual order diverge from source order.
Grid and Flexbox solve different problems. Grid is container-driven and appropriate when two-dimensional alignment across rows and columns matters. Flexbox is content-driven and appropriate when items should size naturally and flow. Both are commonly used together: Grid for overall structure, Flexbox inside individual grid items.