CSS Grid: building layouts in rows and columns
In short: CSS Grid places elements in a two-dimensional grid of rows and columns; it is ideal for whole page layouts, whereas Flexbox suits rows or columns inside single areas.
In more detail: With display: grid a container becomes a grid. You define columns and rows; the children fill the cells automatically or are placed deliberately.
In Depth
Basics
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}fr is a fraction of the free space. gap sets spacing between cells. With grid-column: 1 / 3 an element spans two columns; grid-template-areas allows named areas (“head head”, “side content”).
Responsive without a media query
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); creates as many columns as fit, at least 220 px wide. One column on a phone, four on a desktop, without a single breakpoint. minmax(), auto-fill/auto-fit and aspect-ratio are the key tools.
Grid or Flexbox?
- Grid: two-dimensional, layout from the outside (grid first, content fills).
- Flexbox: one-dimensional, layout from the inside (content decides the size), for example navigation bars.
- Both can be combined: Grid for the page frame, Flexbox for rows inside cells.
- Subgrid (
grid-template-columns: subgrid) lets children use the parent grid’s tracks; available in current browsers.
Avoiding mistakes
- Too many fixed pixel values; prefer
fr,minmax,%. - Do not rearrange the order only visually: tab and screen-reader order follows the source.
- Use the browsers’ grid tools in developer tools to make tracks visible.
See also: Flexbox, Media queries and breakpoints, Tailwind CSS