CSS Subgrid Explained

The Problem Subgrid Solves

Normally, a grid placed inside a grid item creates its own independent set of tracks - it has no awareness of the parent grid's column or row sizes. This makes it hard to keep nested content, like a card's internal header/body/footer, aligned across many sibling cards that might have slightly different content heights.

What subgrid Does

.card-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: auto auto auto;
}
.card {
  display: grid;
  grid-row: span 3;
  grid-template-rows: subgrid; /* inherits the parent's row tracks */
}

With grid-template-rows: subgrid, the card's internal rows line up exactly with the parent grid's row tracks, instead of sizing independently based on its own content.

Why This Matters for Card Layouts

Without subgrid, three cards side by side with different amounts of text in their headers would have misaligned bodies and footers - each card sizes its own rows independently. Subgrid lets every card's header, body and footer align perfectly across the row, because they all share the same underlying row tracks.

Subgrid Also Works for Columns

.item {
  grid-template-columns: subgrid;
}

A Practical Note on Support

Subgrid is supported in all current major browsers, but for a project that must support much older browsers, a fallback layout (or accepting slightly independent alignment) should be planned as a backup.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.