grid-auto-flow

Definition

The grid-auto-flow CSS property is used in grid layouts to control how additional grid items are automatically placed into the grid when there is no explicit placement defined for them.

The grid-auto-flow property accepts several values:

  • row (default): Automatically places grid items in rows, filling each row before moving on to the next.
  • column: Automatically places grid items in columns, filling each column before moving on to the next.
  • dense: Similar to row or column, but attempts to fill in any empty grid cells to minimize gaps.

Here’s an example:

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-flow: column;
}

In this example, the grid-auto-flow: column; rule sets the automatic placement of additional grid items in columns. The grid is defined with three columns using grid-template-columns, and any additional items beyond the defined grid will be placed in subsequent columns, creating a column-based grid structure.

The grid-auto-flow property provides control over how additional grid items are placed when there is no explicit placement defined, allowing for flexible and dynamic grid layouts.

Syntax

.cards {
  display: grid;
  grid-auto-flow: row dense;
}

Values

  • row, column, dense, combinations (row dense).

Practical Examples

.cards {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  grid-auto-flow: row dense;

Control how auto-placed items fill gaps in the grid.

HTML
Item A
Item B (span 2)
Item C
Item D
Code
<div class="grid gap-4 rounded-xl border border-slate-200 bg-white p-4 shadow-sm" style="display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); grid-auto-flow: row dense; gap:1rem;">
  <div class="rounded-lg bg-slate-100 p-4 text-sm text-slate-700">Item A</div>
  <div class="rounded-lg bg-slate-100 p-4 text-sm text-slate-700" style="grid-column: span 2;">Item B (span 2)</div>
  <div class="rounded-lg bg-slate-100 p-4 text-sm text-slate-700">Item C</div>
  <div class="rounded-lg bg-slate-100 p-4 text-sm text-slate-700">Item D</div>
</div>

Tips & Best Practices

  • Use dense to backfill gaps caused by spanning items.
  • Switch to column for horizontal auto-placement.

Accessibility & UX Notes

Dense packing helps avoid large whitespace gaps in card collections.

Browser Support

Supported broadly.

  • grid-auto-columns, grid-auto-rows.
  • grid-template for explicit layouts.