CSS

Optimize Grid Item Packing with grid-auto-flow: dense

Learn how `grid-auto-flow: dense` in CSS Grid helps to fill empty spaces and optimize layout by placing smaller items into available gaps, creating a more compact design.

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); /* Responsive columns */
  grid-auto-rows: 100px; /* Fixed row height for simpler packing demo */
  grid-auto-flow: dense; /* Enables dense packing */
  gap: 10px;
  width: 100%;
  max-width: 800px;
  margin: 20px auto;
  border: 1px solid #ddd;
  padding: 10px;
}

.grid-item {
  background-color: #a7d9f2;
  border: 1px solid #7cbcdb;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2em;
  font-weight: bold;
}

/* Example: make some items span multiple rows/columns */
.grid-item:nth-child(2) {
  grid-column: span 2;
  background-color: #ffcc80;
}
.grid-item:nth-child(5) {
  grid-row: span 2;
  background-color: #b0e0a5;
}
.grid-item:nth-child(8) {
  grid-column: span 3;
  grid-row: span 2;
  background-color: #e0b0e0;
}
How it works: The `grid-auto-flow: dense` property is a powerful feature in CSS Grid for optimizing space utilization. When items are auto-placed and vary in size (e.g., spanning multiple rows or columns), `dense` packing allows the auto-placement algorithm to 'backtrack' and fill any empty gaps left by larger items with subsequent smaller items. This creates a more compact and efficient layout, preventing large blank spaces that might occur with the default `sparse` packing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs