
CSS Grid lays out items in rows and columns. Use it when elements need to align in two dimensions, such as a gallery or a page layout.
1. Create a grid container
Use display: grid for a block-level grid or inline-grid when the grid participates in inline layout. Direct children become grid items.
2. Define columns and rows
Use grid-template-columns and grid-template-rows to describe explicit tracks. A length sets a fixed track; fr distributes available space. repeat() avoids writing the same track repeatedly.
.layout { display: grid; grid-template-columns: 2fr 1fr; grid-template-rows: auto 1fr; }3. Add horizontal and vertical gaps
column-gap separates columns and row-gap separates rows. The gap shorthand takes row spacing first and column spacing second. Older code may use grid-gap.
.layout { gap: 1rem 2rem; }4. Create a flexible gallery
Use minmax() for a lower and upper bound. Combine repeat(), auto-fit, and flexible units so cards can reflow as available width changes.
.gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); gap: 1rem; }5. Practice
Create a two-column layout, inspect the grid lines in DevTools, then vary the viewport width. Ensure items remain in a sensible reading order.