Codectionary / Developer documentation / CSS

Dense Grid Packing and Reading Order

Dense auto-placement lets the grid algorithm revisit earlier gaps when a later item can fit.

What it is and why to use it

Dense auto-placement lets the grid algorithm revisit earlier gaps when a later item can fit. It can reduce empty spaces in a visual gallery, but may place later document content before earlier content on screen. This makes it a deliberate presentation choice rather than a harmless packing optimisation.

Common mistakes and limitations

Dense packing does not reorder the DOM or ordinary sequential keyboard navigation. Avoid it for numbered instructions, forms or other sequences whose order carries meaning. Test both visual and nonvisual reading paths.

Try the example

The example pairs editable CSS with its own HTML preview. Run it, then change one declaration at a time and compare the result. Locally, put the CSS in a style element in the document head or in an external stylesheet linked from the HTML. Feature support varies by browser and version; use the linked reference and a useful fallback where needed.

HTML used by this example

<div class="gallery"><div class="tile wide">1</div><div class="tile wide">2</div><div class="tile">3</div></div>

Syntax

grid-auto-flow: row dense;

Examples

Dense Grid Packing and Reading Order

Run the CSS against the supplied HTML, then experiment with the values.

.gallery { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-flow: row dense; gap: .5rem; }
.tile { background: #dbeafe; color: #172b4d; padding: 1rem; }
.wide { grid-column: span 2; }
  1. Tile 1 spans two columns, leaving a one-column gap.
  2. Tile 2 also needs two columns and moves to the next row; tile 3 can backfill the earlier gap.
  3. The visual order can become 1,3,2 while document order remains 1,2,3. Use this only where that difference does not damage understanding or navigation.
HTML used by this example
<div class="demo"><div class="gallery"><div class="tile wide">1</div><div class="tile wide">2</div><div class="tile">3</div></div></div>

Best practices

  • Dense packing does not reorder the DOM or ordinary sequential keyboard navigation. Avoid it for numbered instructions, forms or other sequences whose order carries meaning. Test both visual and nonvisual reading paths.
  • Inspect the relevant browser reference and test the browsers used by your audience.

Runtime & versions

Web browsers. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

CSS specifications (modules)

Specifications & further reading