2 min read

CSS Grid Auto-Placement

When you define a grid layout, you can explicitly place items into specific cells. However, if you don't specify a position for some items, the CSS Grid Auto-Placement algorithm kicks in to automatically place them in empty cells.

1. The Implicit Grid

If you place an item outside of the columns and rows you defined in grid-template-columns and grid-template-rows, the browser creates implicit tracks to hold that item.

You can control the size of these implicit tracks using:

  • grid-auto-rows: Defines the size of implicitly created rows.
  • grid-auto-columns: Defines the size of implicitly created columns.
.container {
  display: grid;
  grid-template-columns: 100px 100px;
  /* Explicit rows not defined, so all rows are implicit */
  grid-auto-rows: 50px; 
}

2. grid-auto-flow

The grid-auto-flow property controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.

Syntax: grid-auto-flow: [row | column] || dense;

row (Default)

The auto-placement algorithm fills each row in turn, adding new rows as necessary.

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

column

The auto-placement algorithm fills each column in turn, adding new columns as necessary.

.container {
  display: grid;
  grid-template-rows: repeat(3, 100px);
  grid-auto-flow: column;
}

dense

The dense keyword attempts to fill in holes earlier in the grid if smaller items come up later in the sequence. This can change the visual order of items compared to the source order (DOM order), which might be bad for accessibility but good for packing layouts (like masonry).

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

3. Example: Dense Packing

Imagine a grid where some items span 2 columns. Without dense, this might leave gaps. If grid-auto-flow: dense is set, the browser will go back and fill those gaps with subsequent smaller items if they fit.

programming/css/css programming/css/grid-layout