← Back to all snippets
CSS

Aligning Nested Grid Items with CSS Subgrid

Learn how to use CSS Subgrid to achieve perfect alignment between nested grid layouts, ensuring child items inherit and align with parent grid tracks.

.parent-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* Define parent columns */
  gap: 20px;
  padding: 20px;
  border: 1px solid #ccc;
}

.grid-item {
  background-color: #f0f0f0;
  padding: 15px;
  border: 1px dashed #aaa;
  grid-column: span 2; /* This item spans two parent columns */
}

.subgrid-container {
  display: grid;
  grid-column: 1 / -1; /* Make subgrid span all parent columns */
  grid-template-columns: subgrid; /* Inherit parent's column tracks */
  gap: 10px; /* Gap within the subgrid */
  padding: 10px;
  background-color: #e0e0e0;
  border: 1px solid #999;
}

.subgrid-item {
  background-color: #d0d0d0;
  padding: 8px;
  border: 1px dotted #777;
  /* Now these items align perfectly with parent's columns */
  grid-column: 2 / span 1; /* Example: aligns to the 2nd parent column */
}
How it works: This snippet showcases CSS `subgrid`, a powerful feature that allows a nested grid to adopt the track sizing of its parent grid. By setting `grid-template-columns: subgrid;`, the `.subgrid-container` inherits the columns defined in `.parent-grid`. This enables its `.subgrid-item` children to align precisely with the parent grid's tracks, facilitating complex, perfectly aligned layouts without manual calculations or redundant definitions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs