Academy / Advanced Level: HTML and CSS

CSS Grid Advanced Features

Auto-Placement and Dense Packing with grid-auto-flow

By default, grid items are placed in rows and columns in the order they appear in the HTML. The grid-auto-flow property controls how the browser places items in the grid.

  • row (default): Items are placed in rows.
  • column: Items are placed in columns.
  • dense: Allows the grid to fill in gaps more efficiently by backfilling empty spaces.

Example:

.grid-container {
display: grid;
grid-auto-flow: dense; /* Fill gaps if smaller items fit */
grid-template-columns: repeat(3, 1fr);
}

The dense keyword is useful when items of different sizes create gaps in the grid, as it tries to fill these gaps with smaller items.