CSS
Intelligent Auto-Placement for Gap-Filling Grid Layouts
Implement an efficient grid layout that automatically fills available gaps with varying-sized items using 'grid-auto-flow: dense', ideal for dashboards and galleries.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Grid Auto-Flow Dense</title>
<style>
body {
font-family: sans-serif;
background-color: #f8f8f8;
padding: 20px;
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
grid-auto-rows: minmax(80px, auto); /* Height for auto-placed rows */
grid-auto-flow: dense; /* Crucial for gap filling */
gap: 10px;
border: 2px solid #ccc;
padding: 10px;
max-width: 900px;
margin: 0 auto;
}
.grid-item {
background-color: #e0f2f7;
border: 1px solid #a7d9eb;
padding: 15px;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 1.2em;
color: #333;
}
/* Items spanning multiple columns/rows */
.item-span-2-col { grid-column: span 2; background-color: #c8e6c9; border-color: #8bc34a; }
.item-span-2-row { grid-row: span 2; background-color: #ffe0b2; border-color: #ff9800; }
.item-span-2-both { grid-column: span 2; grid-row: span 2; background-color: #ffcdd2; border-color: #f44336; }
</style>
</head>
<body>
<h1>CSS Grid with 'grid-auto-flow: dense'</h1>
<p>This layout intelligently fills empty spaces with smaller items, optimizing item placement.</p>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item item-span-2-col">2 (2 Col)</div>
<div class="grid-item">3</div>
<div class="grid-item item-span-2-row">4 (2 Row)</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item item-span-2-both">7 (2 Col, 2 Row)</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
<div class="grid-item">10</div>
<div class="grid-item">11</div>
<div class="grid-item">12</div>
<div class="grid-item">13</div>
</div>
</body>
</html>
How it works: This snippet demonstrates the powerful `grid-auto-flow: dense` property in CSS Grid. When you have items of varying sizes (some spanning multiple columns or rows), `dense` packing algorithm attempts to fill any holes earlier in the grid. Without `dense`, the default is `row` (or `column`), which only places items in the next available space, often leaving empty gaps. `dense` allows for a more compact and optimized layout, crucial for dynamic dashboards, photo galleries, or content feeds where items need to fit together as efficiently as possible without explicit manual placement for every item.