CSS Grid overview

CSS Grid is a two-dimensional layout system — it controls rows and columns at the same time. It is the best tool for overall page structure, magazine-style layouts, and any design where items need to align both horizontally and vertically.

CSS Grid vs. Flexbox

Both are modern layout tools, and they work well together. The key distinction:

  • Use Flexbox when you need to align items along a single axis — a navigation row, a row of cards, or centering a single element.
  • Use CSS Grid when the layout needs both row and column control — a full page template, a photo gallery, or any design where rows and columns must align with each other.

Grid terminology

Grid container — The element with display: grid. All layout rules start here.

Grid items — The direct children of the grid container. These are the elements placed into the grid.

Grid lines — The horizontal and vertical dividing lines that make up the grid structure. They are numbered starting at 1.

Grid tracks — The rows and columns themselves — the space between two adjacent grid lines.

Grid areas — A rectangular region spanning one or more cells. Named areas let you reference regions by name (e.g., header, sidebar) instead of line numbers.

Grid gap — The space between tracks. Set with gap, row-gap, or column-gap.

Defining the grid

Enable Grid by setting display: grid on a container, then define the track structure:

grid-template-columns: 200px 1fr 1fr;
grid-template-rows: auto 1fr auto;

This creates three columns (one fixed, two flexible) and three rows.

The fr unit

fr stands for fractional unit. It represents a share of the remaining available space in the grid container after fixed-size tracks are subtracted.

grid-template-columns: 1fr 2fr 1fr;

The middle column gets twice as much space as the two side columns. Unlike percentages, fr accounts for gap automatically.

auto vs. fr vs. px

UnitBehavior
pxFixed size — doesn’t flex
%Percentage of the container
autoSizes to the content
frTakes a share of remaining space
minmax(200px, 1fr)At least 200 px, grows with available space

The gap property

gap sets uniform space between all tracks. Use row-gap and column-gap separately when you need different spacing in each direction.

gap: 1.5rem;           /* equal row and column gap */
row-gap: 2rem;         /* rows only */
column-gap: 1rem;      /* columns only */

Implicit vs. explicit grid

The explicit grid is the one you define with grid-template-columns and grid-template-rows. If you place more items than the defined grid has cells, the browser creates additional rows automatically — that’s the implicit grid. You can style implicit rows with grid-auto-rows.