|$ curl https://forge-ai.dev/api/markdown?path=docs/css/subgrid
$cat docs/css-subgrid.md
updated Recently·22 min read·published
CSS Subgrid
◆CSS◆Grid◆Advanced
Introduction
Subgrid (grid-template-columns: subgrid / grid-template-rows: subgrid) allows a nested grid to inherit the track sizing of its parent grid. Instead of defining its own column or row sizes, a subgrid aligns its children to the parent's grid lines.
Basic Subgrid
Apply subgrid to a grid item that itself uses display: grid. The nested grid inherits the parent's column tracks.
subgrid-basic.css
CSS
| 1 | .parent { |
| 2 | display: grid; |
| 3 | grid-template-columns: 1fr 2fr 1fr; |
| 4 | gap: 16px; |
| 5 | } |
| 6 | |
| 7 | .child { |
| 8 | grid-column: 1 / -1; |
| 9 | display: grid; |
| 10 | grid-template-columns: subgrid; |
| 11 | /* Inherits 1fr 2fr 1fr from parent */ |
| 12 | } |
| 13 | |
| 14 | .child-item { |
| 15 | /* Aligns to parent grid lines directly */ |
| 16 | grid-column: 2 / 3; |
| 17 | } |
Common Use Cases
Subgrid is ideal for aligning form labels and inputs across multiple rows, keeping card components aligned within a grid, and building consistent table-like layouts without HTML tables.
subgrid-forms.html
HTML
| 1 | <div class="form-grid"> |
| 2 | <div class="form-row"> |
| 3 | <label>Name</label> |
| 4 | <input type="text" /> |
| 5 | <span class="hint">Full name</span> |
| 6 | </div> |
| 7 | <div class="form-row"> |
| 8 | <label>Email</label> |
| 9 | <input type="email" /> |
| 10 | <span class="hint">Valid email</span> |
| 11 | </div> |
| 12 | </div> |
| 13 | |
| 14 | <style> |
| 15 | .form-grid { |
| 16 | display: grid; |
| 17 | grid-template-columns: 120px 1fr 80px; |
| 18 | gap: 8px; |
| 19 | } |
| 20 | .form-row { |
| 21 | display: grid; |
| 22 | grid-column: 1 / -1; |
| 23 | grid-template-columns: subgrid; |
| 24 | } |
| 25 | </style> |
ℹ
info
Subgrid only works when the parent grid explicitly defines track sizes — it cannot inherit from auto-sized implicit tracks.