What is the difference between auto-fill and auto-fit in CSS Grid? Comparing empty tracks with a slider

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this articleThis article was created using an automated generation workflow powered by generative AI. We verified the W3C CSS Grid specification and MDN function documentation, and inspected the track widths in Chromium when providing the same width and card count.

Verification Status: 🧪 Confirmed in official specifications and local browsers. Card counts and track widths were verified under six conditions. Access to the public demo page and other browsers have not been verified.

When there are few cards, you might want to leave whitespace on the right side of the list, or you might want to enlarge the cards to fill the entire container. CSS Grid's auto-fill and auto-fit allow you to express these design differences in how tracks are handled. Let's place two identical cards and observe the differences while changing the container width.

Try it out first

Open the interactive live demo(Access to public URL unverified)

You can also refer tothe tutorial README and complete version.

ItemContent
Target AudienceCSS Grid-compatible browsers, JavaScript enabled
Required LibrariesNone. Uses standard HTML, CSS, and JavaScript features
Data and PermissionsFictional cards only. No login or location permissions required
Network TrafficNo external communication is added other than fetching the page.
OperationAdjust the "Container Width" and "Card Count" sliders.
  1. Keep the initial container width at 540px and the card count at 2, and compare the cards in the auto-fill layout above with the auto-fit layout below.

  2. Look at the "Column Width" values below the cards. The top layout shows four 126px columns, while the bottom shows two 264px columns and two 0px columns.

  3. Change the card count to 4. Verify that the widths of the top and bottom cards become equal.

  4. Set the card count to 5. A single card appears on the second row. Even with the bottom method, the final single card does not stretch across the entire width.

  5. Reset the card count to 1 and change the container width from 252px to 251px. Just a 1px change in width switches the number of columns in the top method from 2 to 1.

If the comparison containers are wider than the screen on a smartphone or similar device, you can scroll horizontally within each container. This is a design specific to this learning material to ensure the tested widths are not restricted by screen width. The width value can also be adjusted by focusing on the slider and using the arrow keys. To return to the initial conditions, set them to 540 and 2.

If you cannot open the demo page, retrieve index.html and app.js from the fixed commit of the learning material into the same folder and open them using a method permitted by your operating environment. Cards will not be generated if JavaScript is disabled. You can also read the CSS in the next section and try it with static HTML first.

Leaving Empty Columns or Collapsing Them

In CSS Grid, a column is not the card itself. It is a vertical section prepared to place cards, also called a grid track. Sections without cards can still have width. Conversely, even if a column definition exists, unused portions may be treated as having a width of 0px.

In this experiment, the minimum column width was set to 120px and the gap between columns to 12px. auto-fill pre-creates columns that fit within the container. Even with only 2 cards, it maintains space for 4 columns, so a space equivalent to the remaining 2 columns is visible on the right. auto-fit collapses repeated columns where no cards are placed in any row. The remaining 2 columns use the leftover width.

The empty columns referred to here do not mean blank cells visible at the end of a row. Looking at the column as a whole, it depends on whether items in normal flow are placed in it or span across it. In the example where 5 cards are arranged in 4 columns, all 4 columns are used in the first row. Even if the remaining 3 cells in the second row are empty, the column as a whole is not empty, so auto-fit does not collapse the columns.

W3C CSS Grid Layout Module Level 2 — auto-repeatdistinguishes between automatic repetition and the collapse of empty tracks. This specification document is a Candidate Recommendation Draft dated March 26, 2025, and served as the basis for verifying the behaviors handled here.

Key Parts of the Code

.grid {
  display: grid;
  gap: 12px;
}

.fill {
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
}

.fit {
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
}

display: grid allows child elements to be placed on a grid. grid-template-columns specifies the columns to be prepared horizontally. The first argument of repeat specifies the repetition pattern, and the second argument defines the column to be repeated. minmax(120px, 1fr) specifies a minimum column width of 120px and a flexible value of 1fr used for distributing remaining width. It does not specify the font size or image width within the columns.

1fr is not a fixed fraction of the entire screen width. It is a unit used to distribute available width to flexible columns while taking into account necessary spacing and the sizes of other columns. When the same specification is repeated as in this case, the remaining columns will have equal widths. Because gaps adjacent to collapsed columns are also collapsed, simply setting the column width to 0 does not leave all of the original spacing intact.

Details on function argumentsYou can refer to MDN repeat().andMDN minmax().can be referenced.

The JavaScript in the tutorial sets the values obtained from the slider to the upper and lower grids under the same conditions. It creates card elements and inserts dummy labels using textContent. Finally, it uses getComputedStyle(grid).gridTemplateColumns to retrieve the column widths resolved by the browser. It does not render the number of columns or card widths using custom JavaScript calculations; CSS itself determines the layout, and the resulting values are read out so they can also be compared numerically.

Try guessing the numbers and then changing them

Container Width (px)Number of Cardsauto-fill Column Width (px)auto-fit Column Width (px)
5402126,126,126,126264,264,0,0
5404126,126,126,126Same as above
5405126, 126, 126, 126Ditto
2521120, 120252, 0
2511251251
1202120120

The table values are obtained by loading the same CSS and card generation code from the course material into a local instance of Chromium. The minimum required width for four columns is 516px, which is the sum of four 120px widths (480px) and three 12px gaps (36px). A 540px container can accommodate four columns, but five columns require 648px, so it is limited to four columns. The width distributed to each column using auto-fill is 126px, calculated by subtracting 36 from 540 to get 504, and dividing by 4.

When using auto-fit with only two cards, 528px (obtained by subtracting the 12px gap between the two used columns) is distributed across the two columns. Each card can expand to 264px. Furthermore, 252px is the threshold representing the minimum width of two columns (240px) plus the 12px gap. At 251px, two columns can no longer be rendered, resulting in both falling back to a single column. This explanation focuses exclusively on placing cards sequentially using the same fixed container width and minimum column width as the course material, and should not be directly generalized to complex grids.

Next, let us fix the number of cards at two and gradually widen the container. We will identify the thresholds where space increases or additional columns are created with auto-fill. With auto-fit, the same two items expand, but if the container is too narrow to fit more than one column, both methods behave identically. Changing the width and the number of cards simultaneously makes it difficult to determine what caused the visual change, so only one value should be adjusted at a time.

If you copied the course material, try changing the minimum width of 120px for both to 160px. By predicting at which width it switches to two columns, you can verify how the minimum width and gap determine the column count. Rather than comparing purely by visual appearance under the initial conditions, recording the conditions before and after the change makes it easier to explain the cause.

Troubleshooting

SymptomThings to checkNext steps
Cards are not displayedPlacement of app.js, enabling JavaScript, and Developer Tools ConsolePlace HTML and JS in the same folder
The top and bottom appearances are identicalWidth and number of cards, whether all columns are utilizedRevert to 540px and 2 cards for comparison
The right edge is not visible on smartphonesHorizontal scrolling for each comparison container in the tutorialReduce container width or enable scrolling within the container
Text overflowsLong strings, minimum card width, and text wrappingIn production, also verify long names and zoomed displays
Decimal values appear in numbersWidth division and browser roundingDo not immediately assume a difference of a few pixels indicates a functional defect

In production sites, if the viewport width is narrower than the minimum column width, the specified 120px column may exceed the container boundary. Since the experiment merely prevents selecting values below 120px, actual pages require separate considerations. For instance, consider specifying restrictions to keep the minimum width at or below the container width, or designing layout switches to a single column on narrow screens. After making changes, verify text scaling, long names, images, and the fit of interactive buttons.

For professional use: Internal portal card list

Imagine a screen displaying link cards for General Affairs, Accounting, and IT departments. Since accessible links vary depending on user permissions, 2 cards may appear for one user and 8 cards for another. Defining grid rules beforehand, rather than determining column counts via JavaScript every time the card count changes, improves maintainability.

For example, when designing a screen based on cards of the same width, use auto-fill as a candidate. Since it reserves empty columns even with a small number of cards, using the same width framework and column definition makes it easier to align column widths across screens with different card counts. On the other hand, if you want to make descriptions easier to read with larger cards when fewer functions are available, consider auto-fit. However, if they become too wide horizontally, sentences may be harder to follow. Design the maximum card width and typography separately.

The choice here is not merely a matter of responsive design. It also represents a difference in information architecture: whether to treat items removed due to permissions as blank space or to expand other items. Note that hiding items using CSS is not a substitute for access control. Authorization checks must be performed at an appropriate layer such as the server side.

After selecting the grid, verify it using combinations of 0 cards, 1 card, the maximum number of cards, long titles, and screen magnification, and display explanations or next actions when empty. The card count in this learning material ranges from 1 to 8, and screens with 0 cards or implementations in other products have not been verified.

Avoid assuming that choosing auto-fit will always expand the cards in the last row. If your requirement is to distribute remaining width row by row, Flexbox wrapping and stretching can also be considered as alternatives. Which is better depends on whether you need to align columns across row gaps or if you want to position each row independently.

Official Information and Verification Scope

Verification date: November 28, 2026. The HTML and JavaScript of the learning material were loaded into memory, and column widths, card counts, and the absence of JavaScript exceptions were verified under six conditions using Chromium 144.0.7559.96. JavaScript syntax checking using Node.js was also performed. Accessing the public demo, behavior in other browsers, direct loading of file URLs, and CodeQL have not been verified. Business screens on the live site have not been modified.

GitHub Sample

Document information

Article title
What is the difference between auto-fill and auto-fit in CSS Grid? Comparing empty tracks with a slider
Published
Updated
Source
https://papanda925.com/?p=18846&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL