ShareYourGroupShareYourGroupCSS Lab

CSS grid guide: columns, fr units, auto-fit and areas

Grid describes a layout in rows and columns, and lets items sit in the cells. It is the best tool for page-level structure.

Tracks, cells and gap

A grid has columns and rows, called tracks. grid-template-columns: 200px 1fr 1fr makes three columns: a fixed 200 pixel one, and two that share the rest equally. Items fill cells from left to right, row by row. gap adds space between tracks.

The fr unit and repeat

1fr means one share of the free space. repeat(4, 1fr) is shorthand for 1fr 1fr 1fr 1fr. minmax(150px, 1fr) is a track that is never narrower than 150 pixels and otherwise takes a share.

A responsive grid with no media query

grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); creates as many columns as fit in the width, each at least 220 pixels. Narrow screens get one column, wide screens several. This single line replaces most card-layout media queries.

Placing and spanning

Put grid-column: span 2 on an item to make it two columns wide, and grid-row: span 2 for two rows tall. You can also give start and end lines: grid-column: 1 / 3 stretches from line 1 to line 3, which covers two columns.

Named areas

For page layouts, give areas names:

.page {
  display: grid;
  grid-template-columns: 220px 1fr;
  grid-template-areas:
    "header header"
    "nav    main"
    "footer footer";
}
header { grid-area: header; }
nav { grid-area: nav; }
main { grid-area: main; }
footer { grid-area: footer; }

On a phone, redefine grid-template-areas in a media query as one column of four rows, and the layout rearranges without touching the HTML.

Alignment

The container has justify-items and align-items for placing items within their cells, and justify-content and align-content for placing the whole grid inside its box. place-items: center is a shorthand for both item properties.

Common problems

What is the difference between auto-fit and auto-fill?

Auto-fill keeps empty tracks; auto-fit collapses them so the items can grow into the free space.

Can I nest grids?

Yes. An item can itself be a grid. The newer subgrid value lets the nested grid share the parent's tracks, where supported.

This is an independent site. It is not connected with the W3C, MDN, Google, Apple, Mozilla or Microsoft. Browser and product names belong to their owners.