← Back to all snippets
CSS

CSS Grid `subgrid` for Nested Component Alignment

Utilize CSS `subgrid` to effortlessly align nested grid items with their parent grid's tracks, maintaining perfect column and row integrity in complex layouts.

.parent-grid {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 20px;
  padding: 20px;
  border: 1px solid #ccc;
}

.nested-component {
  grid-column: 2 / span 2; /* Component starts in 2nd column, spans 2 */
  display: grid;
  grid-template-columns: subgrid; /* Inherits parent's column tracks */
  grid-column: 1 / -1; /* This subgrid now spans its own allotted space */
  background-color: #f0f8ff;
  padding: 10px;
  border: 1px dashed #aaa;
}

.nested-item-1 {
  grid-column: 1; /* Aligns with the first track within subgrid's span */
  background-color: #d1e7dd;
}

.nested-item-2 {
  grid-column: 2; /* Aligns with the second track within subgrid's span */
  background-color: #d1e7dd;
}
How it works: This snippet demonstrates the powerful `subgrid` feature in CSS Grid, allowing a nested grid to inherit the track sizing from its parent grid. By setting `grid-template-columns: subgrid` on the `.nested-component`, its internal columns automatically align with the parent's defined tracks within its allocated `grid-column` span. Its direct children can then align precisely within those inherited tracks, making complex multi-level layouts perfectly aligned.

Need help integrating this into your project?

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

Hire DigitalCodeLabs