CSS

Controlling Auto-Placement Direction in CSS Grid with `grid-auto-flow`

Learn to direct how unpositioned items fill your CSS Grid with `grid-auto-flow`, utilizing `row`, `column`, and `dense` strategies for efficient layouts.

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* 3 columns */
    grid-template-rows: repeat(2, 100px); /* 2 rows */
    gap: 10px;
    border: 1px solid #000;
    /* Controls how auto-placed items fill the grid */
    /* Options: row (default), column, row dense, column dense */
    grid-auto-flow: row dense;
    /* Try grid-auto-flow: column; to see items fill columns first */
    /* Try grid-auto-flow: column dense; to fill gaps in columns */
}

.grid-item {
    background-color: #e0f7fa;
    padding: 10px;
    border: 1px solid #00bcd4;
    text-align: center;
}

/* An item that spans multiple columns, potentially creating a gap */
.grid-item-2 {
    grid-column: span 2;
    background-color: #ffecb3;
    border-color: #ffc107;
}

/* An item that spans multiple rows */
.grid-item-5 {
    grid-row: span 2;
    background-color: #c8e6c9;
    border-color: #4caf50;
}
How it works: The `grid-auto-flow` property determines how items that are not explicitly positioned (`grid-row`/`grid-column`) are placed into the grid. By default, it's `row`, filling rows first. Setting it to `column` fills columns first. Adding `dense` (e.g., `row dense` or `column dense`) allows the algorithm to backfill any empty spaces with smaller items, optimizing space usage but potentially changing the visual order of items.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs