CSS Grid Layout
How CSS Grid Works
Grid lets you define a two-dimensional layout with rows and columns. Set display: grid on a container, define your track sizes, and child elements slot into cells automatically. Unlike flexbox, grid controls both dimensions at once.
Think of it as defining a spreadsheet structure: you declare how many columns and rows you want, how big they are, and then place items into that structure. Items can span multiple cells, and tracks can be fixed, flexible, or content-sized.
Basic Grid
The fr Unit
fr means “fraction of remaining space.” After fixed-size tracks take their space, fr divides what is left.
Responsive Grid with auto-fit
This is the most useful grid pattern. No media queries needed — columns reflow automatically:
Each column is at least 200px. As the container shrinks, columns drop to the next row. As it grows, more columns appear. Resize your browser to see it.
Grid Template Areas
Name regions of your layout and assign items to them. Great for page-level structure:
Spanning Columns and Rows
Alignment in Grid
Grid uses the same alignment properties as flexbox, plus a few extras:
- justify-items / align-items — align all items within their cells
- justify-content / align-content — align the grid tracks within the container
- justify-self / align-self — align a single item within its cell
- place-items — shorthand for
align-items justify-items
Frequently Asked Questions
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)). Columns auto-reflow as the viewport changes. Each column is at least 250px, and they grow to fill remaining space.fr stands for “fraction of available space.” 1fr 2fr means the second track gets twice the space of the first. It only divides space remaining after fixed tracks (px, auto) are calculated.