Grid alignment and subgrid
Definition and purpose
Grid alignment positions items inside their grid areas and positions the grid tracks inside the container. Subgrid lets a nested grid borrow the parent grid’s tracks along an axis instead of creating independently sized tracks there.
Center inside each area
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: grid; grid-template-columns: 120px 180px; grid-auto-rows: 60px; justify-items: center; align-items: center; } #p > div { width: 40px; height: 20px; } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The items are centered inside their individual areas, not the entire grid.
Syntax and mental model
justify-items aligns items on the inline axis and align-items on the block axis. justify-content and align-content position tracks when there is extra space. A child spanning two parent columns can use display: grid; grid-template-columns: subgrid to share those columns. The other axis can remain independently sized.
Share parent column tracks
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #p { width: 300px; } #p > div { background: lightblue; outline: 1px solid navy; } #p { display: grid; grid-template-columns: 100px 180px; gap: 20px; } #a { grid-column: 1 / 3; display: grid; grid-template-columns: subgrid; } </style> </head> <body> <div id="p"> <div id="a"> <span id="x">Name</span> <span id="y">Value</span> </div> <div id="b">Note</div> <div id="c">Action</div> </div> </body></html>The second nested cell aligns with the second parent column.
Common mistakes
A nested grid with its own column definitions does not automatically share parent tracks. Subgrid requires the relevant parent grid span; use an independent nested layout as a fallback where necessary.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Responsive auto-fill and auto-fit. Next lesson: Grid versus flex and composition.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Grid alignment and subgrid — knowledge check
Five questions on grid alignment and subgrid.
Which property aligns grid items along the inline axis inside their areas?
What does align-content position in a grid?
What does grid-template-columns: subgrid share?
Can the other axis remain independent?
Does a nested grid with 1fr 1fr necessarily match parent tracks?