CSS
Efficient Grid Item Packing with grid-auto-flow: dense
Optimize your CSS Grid layouts by using `grid-auto-flow: dense` to automatically fill gaps left by items of varying sizes, ensuring a compact and efficient arrangement.
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); /* Responsive columns */
grid-auto-rows: 100px; /* Each row implicitly 100px tall */
gap: 10px;
width: 100%;
max-width: 800px;
border: 2px solid #673AB7;
padding: 10px;
margin: 20px auto;
grid-auto-flow: dense; /* Crucial for dense packing */
}
.grid-item {
background-color: #ede7f6;
border: 1px solid #512DA8;
display: flex;
justify-content: center;
align-items: center;
font-family: sans-serif;
font-weight: bold;
color: #311B92;
}
/* Items with varying sizes */
.item-wide {
grid-column: span 2; /* Span two columns */
background-color: #d1c4e9;
}
.item-tall {
grid-row: span 2; /* Span two rows */
background-color: #b39ddb;
}
.item-large {
grid-column: span 2;
grid-row: span 2;
background-color: #9575cd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Dense Packing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Grid Auto Flow: Dense</h1>
<p>Observe how the items rearrange to fill empty spaces when 'dense' is applied.</p>
<div class="grid-container">
<div class="grid-item item-large">Large (2x2)</div>
<div class="grid-item">Item 1</div>
<div class="grid-item item-tall">Tall (1x2)</div>
<div class="grid-item">Item 2</div>
<div class="grid-item item-wide">Wide (2x1)</div>
<div class="grid-item">Item 3</div>
<div class="grid-item">Item 4</div>
<div class="grid-item item-tall">Tall (1x2)</div>
<div class="grid-item">Item 5</div>
<div class="grid-item item-wide">Wide (2x1)</div>
<div class="grid-item">Item 6</div>
<div class="grid-item">Item 7</div>
</div>
</body>
</html>
How it works: This snippet demonstrates `grid-auto-flow: dense`, a powerful CSS Grid property for efficiently packing items. When items in a grid have different sizes (spanning multiple columns or rows), `grid-auto-flow: row` (the default) might leave empty gaps. By setting `grid-auto-flow: dense`, the browser will attempt to fill these gaps with subsequent items, potentially reordering them visually to create a more compact and space-efficient layout without changing their order in the HTML source. This is excellent for dashboard widgets or varied content blocks.