UndieGravity LogoUndiegravity

CSS Grid vs Flexbox: When to Use Each

Flexbox lays out items in one direction; CSS Grid lays out rows and columns together. Real examples of navbars, card grids, and page layouts with each.

By UndieGravity, , 1 min read

Both Flexbox and Grid are supported by every current browser, and most layouts use both. The simple rule: Flexbox is for one direction, a row or a column. Grid is for two directions, rows and columns at the same time.

Flexbox: a row of things

A navbar is the classic case: a logo on the left, links on the right, everything centered vertically.

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

Flexbox lets content decide the size: each item takes the width it needs, and flex: 1 makes an item take the leftover space. That is ideal for toolbars, button groups, and tags.

Grid: a layout of rows and columns

A card gallery that fits as many columns as the screen allows, with no media queries:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 1.5rem;
}

Grid lets the layout decide the size: you define the columns, and items fill them. Every card in a row lines up, which Flexbox with wrapping cannot guarantee.

A full page layout with Grid

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}

.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }

Named areas make the layout readable at a glance, and changing it for phones is one media query that redefines grid-template-areas.

Quick decision guide

  • Navbar, button row, centered icon and text: Flexbox.
  • Card gallery, image grid, pricing table: Grid.
  • Whole page with header, sidebar, and footer: Grid.
  • Items inside each card: usually Flexbox.

Subgrid for aligned cards

When cards have titles of different lengths, their buttons end up at different heights. grid-template-rows: subgrid lets each card share the parent grid's rows, so titles, text, and buttons line up across the row.

Keep reading