CSS Subgrid
Overview
A massive flaw in CSS Grid used to be that the Grid stopped at the direct children. If you had a row of 3 Cards, you could make the Cards equal heights. BUT, if Card 1 had a massive title, its internal text would misalign with Card 2's internal text. subgrid (fully supported in 2024+) is a revolutionary fix. It allows a child container to 'pierce' its parent's grid boundaries and explicitly inherit its parent's exact track sizing, perfectly aligning nested grandchild elements across completely different cards.
Syntax
/* 1. The Master Grid */
.card-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
/* 2. The Child Card (Also becomes a grid itself!) */
.card {
display: grid;
/*
Instead of defining its own rows...
It explicitly INHERITS the rows from the Master Grid!
*/
grid-template-rows: subgrid;
/* Make the card span 3 rows of the master grid */
grid-row: span 3;
}
/*
Now, the Title, Image, and Button inside Card 1
will perfectly horizontal-align with the Title, Image, and Button in Card 2,
even if the text lengths are wildly different!
*/Common Pitfalls
- Using
subgridwithout settingdisplay: gridon the child.subgridis just a sizing value for tracks. The element itself must still be explicitly declared as a Grid container to use it. - Trying to use
subgridin very old legacy environments. While it has full evergreen browser support as of 2024, older mobile devices might ignore it, causing the nested elements to collapse. Use@supportsto provide fallbacks.
Interview Questions
subgrid solve?Card alignment. When you have multiple cards side-by-side, Flexbox can make the cards the same height. But subgrid ensures the internals (like forcing all the 'Buy Now' buttons to align perfectly at the bottom, or all titles to align at the top) sync perfectly across every card.
Real-World Example
Aligning pricing tiers natively. Tier 1 has 3 features, Tier 3 has 10 features. Subgrid forces all the 'Buy' buttons to align perfectly at the absolute bottom.
.pricing-tier {
display: grid;
/* Inherits the exact row heights from the parent! */
grid-template-rows: subgrid;
grid-row: span 4; /* Header, Price, Features, Button */
}Check Your Knowledge
Test your understanding of CSS Subgrid with these quick questions.