CSS Grid Basics

Flexbox arranges things along a single line. Grid arranges things along two at once — rows and columns together — which makes it the better tool the moment you're laying out a whole page section rather than one row of items.

Turning on grid

Set display: grid on a container, then describe the columns you want with grid-template-columns. The fr unit means "a fraction of the remaining space" — it's grid's own flexible sizing unit:

Try it yourself
Result

Columns don't have to be equal. grid-template-columns: 200px 1fr gives the first column a fixed 200px and lets the second column absorb whatever space is left — a common shape for a sidebar next to a main content area:

Try it yourself
Result

grid-template-rows works the same way for row heights, and rows you don't explicitly define are sized automatically to fit their content.

gap

gap puts consistent spacing between grid cells, both between rows and between columns, without you having to fake it with margin on individual items:

Try it yourself
Result

Placing an item across multiple cells

Any grid item can be told to span more than one column or row with grid-column / grid-row. span 2 means "stretch across two tracks starting from here" — useful for a banner or featured item that should stand out from the regular grid:

Try it yourself
Result

Grid vs. flexbox, at a glance

  • Flexbox is one-dimensional. It's built for arranging items along a single row or column — a nav bar, a button group, a row of cards that should share space evenly.
  • Grid is two-dimensional. It's built for arranging items into rows and columns at the same time — a page layout, a photo gallery, a dashboard of cards that need to line up both horizontally and vertically.
  • They combine well. It's completely normal to use grid for the overall page structure and flexbox inside individual grid cells to line up the content within each one.
Note: if you find yourself asking "how do I control both rows and columns at once here," that's usually the sign you want grid instead of flexbox.