CSS

Creating Aligned Nested Layouts with CSS Subgrid

Leverage CSS Subgrid to inherit track definitions from a parent grid, allowing children within a grid item to align perfectly with the overall page grid structure.

.parent-grid-container {
  display: grid;
  /* Define 3 explicit columns for the parent grid */
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
  padding: 1rem;
  border: 2px dashed #999;
  background-color: #f7f7f7;
}

.parent-grid-item {
  background-color: #e0f0ff;
  border: 1px solid #a0c0e0;
  padding: 1rem;
  text-align: center;
}

/* This item spans two parent grid columns and uses subgrid internally */
.item-with-subgrid {
  grid-column: span 2; /* This item itself spans two columns of the parent grid */
  display: grid;
  grid-template-columns: subgrid; /* The item's internal grid inherits parent's column tracks */
  gap: 0.5rem; /* Gap between subgrid elements */
  border: 2px solid blue;
  padding: 0.5rem;
  background-color: #e6f7ff;
}

/* Child elements of .item-with-subgrid can now align to the parent's grid lines */
.subgrid-element-1 {
  /* This child takes up the first column of the *inherited* subgrid,
     which corresponds to the first column spanned by .item-with-subgrid from the parent */
  grid-column: 1;
  background-color: #cceeff;
  padding: 0.5rem;
  border: 1px solid #99ccee;
}

.subgrid-element-2 {
  /* This child takes up the second column of the *inherited* subgrid,
     which corresponds to the second column spanned by .item-with-subgrid from the parent */
  grid-column: 2;
  background-color: #99ddff;
  padding: 0.5rem;
  border: 1px solid #66bbdd;
}
How it works: Subgrid is a powerful CSS Grid feature that allows a nested grid to inherit the track definitions (columns and rows) of its parent grid. In this snippet, `.parent-grid-container` defines a 3-column grid. The `.item-with-subgrid` spans two of these parent columns (`grid-column: span 2`). By setting `display: grid; grid-template-columns: subgrid;` on this item, its internal children (`.subgrid-element-1`, `.subgrid-element-2`) can now align directly to the *parent grid's column lines* that the `.item-with-subgrid` occupies, ensuring perfect vertical alignment across complex, nested layouts. This is particularly useful for components that need to integrate seamlessly into a larger grid structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs