CSS & LayoutBaseline · Newly

CSS Subgrid

Mental Model

subgrid lets a nested grid adopt its parent's column or row tracks instead of inventing isolated ones. Child items inside sibling cards then participate in the same CSS Grid Track Sizing pass, keeping headings, media, and footers aligned across rows.

Interactive Simulator

Independent Nested Grids vs subgrid

Compare misaligned sibling card internals against shared parent row tracks.

Lines of Code
Before
6
After
6
Reflows / Browser Cost
Before
Isolated per card
After
Single unified pass
BeforeIndependent Card Grids
.cards { display: grid; grid-template-columns: repeat(3, 1fr); }
.card {
  display: grid;
  grid-template-rows: auto 1fr auto;
  /* Titles & footers misalign across cards */
}
Lines: 6Reflows: Isolated per cardDependencies: 0 JS (misaligned rows)

A 2-line title in Card 1 misaligns Card 2’s body and footer.

After (Native)Shared Parent Tracks via subgrid
.cards { display: grid; grid-template-columns: repeat(3, 1fr); }
.card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
}
Lines: 6Reflows: Single unified passDependencies: 0 JS (pixel-aligned)

All card titles, bodies, and footers share the exact same row tracks.

Under the Hood

Without subgrid, each card is an island measuring its own ceiling height; with subgrid, every card bolts its shelves onto the same wall studs.

  1. Track Adoption: Setting grid-template-rows: subgrid maps the child's row lines onto the parent's spanned tracks.
  2. Upward Sizing: Intrinsic content inside the subgrid feeds back into the parent's Render Tree & Layout track-sizing pass, expanding the shared row for all siblings.
  3. Explicit Span: The subgrid container must span enough parent tracks (grid-row: span 3) to hold its internal rows, otherwise extra children pile into the last track.
CSS
.pricing-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 1.5rem;
}
.pricing-card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid;
  row-gap: 0.75rem; /* Overrides parent row-gap locally */
}

Problem Genealogy

  • 2017–2022: display: contents was abused to flatten card wrappers into a parent grid, breaking background, border, and accessibility semantics on the card container.
  • 2023+: CSS Grid Level 2 (subgrid) shipped in all major engines, preserving the card wrapper box while sharing tracks.

Production Pitfalls

Production Pitfall
  • Forgetting grid-row: span N: A card defaults to spanning 1 row; without span N, all 3 subgrid children collide inside that single row.
  • Inherited gap: Subgrids inherit the parent's gap automatically; override row-gap or column-gap on the subgrid if internal spacing should be tighter.
When Not to Use
  • When not to use subgrid: Avoid subgrid when cards have variable numbers of internal sections, use Flexbox margin-top: auto on the footer instead.

Connections & Logical Next Steps

CSS & LayoutCSS Subgrid

Mechanical Comparisons