css html vector image

CSS Subgrid: Mastering Alignment in Nested Layouts

The Problem with Nested Grids

For years, CSS Grid has revolutionized how we build layouts. However, a common frustration remained: nested elements (children of a grid item) could not easily align with the parent grid's tracks. If you had a row of cards with varying content lengths, the headers and footers of those cards wouldn't align horizontally because each card created its own independent grid context.

Developers often resorted to fixed heights or complex JavaScript calculations to keep elements lined up. CSS Subgrid solves this by allowing a child element to 'inherit' the grid tracks of its parent.

How Subgrid Works

To use subgrid, you first define a parent grid. Then, you make the child element a grid item and set its grid-template-rows or grid-template-columns to subgrid. This tells the child to use the parent's defined tracks instead of creating new ones.

Example: Aligning Card Headers and Footers

Imagine a layout with three cards. Each card has a header, a body, and a footer. Without subgrid, a long body in card one won't affect the footer position in card two. With subgrid, they stay perfectly aligned.

<div class="container">\n  <div class="card">\n    <header>Short Title</header>\n    <div class="content">Small bit of text.</div>\n    <footer>Button</footer>\n  </div>\n  <div class="card">\n    <header>A Much Longer Title That Wraps</header>\n    <div class="content">More content here...</div>\n    <footer>Button</footer>\n  </div>\n</div>

The CSS would look like this:

.container {\n  display: grid;\n  grid-template-columns: repeat(2, 1fr);\n  /* Define 3 rows for all cards to share */\n  grid-template-rows: auto 1fr auto;\n  gap: 20px;\n}\n\n.card {\n  display: grid;\n  /* This is the magic: it spans 3 rows of the parent */\n  grid-row: span 3;\n  /* And tells those rows to follow the parent grid */\n  grid-template-rows: subgrid;\n  border: 1px solid #ccc;\n  padding: 10px;\n}

Why This Matters

Subgrid is particularly powerful for UI components like form labels and inputs. By using grid-template-columns: subgrid, you can ensure that labels in different containers always have the same width, aligned perfectly to the overall page structure. This eliminates the need for 'magic number' widths or fragile flexbox hacks.

Browser Support and Best Practices

As of 2024, CSS Subgrid has excellent support across all modern evergreen browsers (Chrome, Firefox, Safari, and Edge). However, if you must support legacy browsers, ensure you provide a fallback. A common strategy is to use a standard grid or flexbox layout first, then wrap the subgrid logic in a @supports rule.

@supports (grid-template-rows: subgrid) {\n  .card {\n    grid-template-rows: subgrid;\n  }\n}

Subgrid is more than just a convenience; it is the final piece of the CSS Grid puzzle that allows for truly cohesive, component-based design systems where nested elements respect the global layout.