DevLab
CSS

Flexbox vs CSS Grid: When to Use Each

Learn the fundamental difference between one-dimensional Flexbox and two-dimensional Grid, with practical examples for navbars, galleries, and page layouts.

The One-Sentence Rule

Flexbox is for rows or columns. Grid is for rows and columns simultaneously.

Laying out items in a single direction — a navbar, a row of cards, a vertical sidebar — use Flexbox. Controlling items in two dimensions at once — a dashboard, a photo gallery, a page layout with header, sidebar, main, and footer — use Grid.

Flexbox in Practice

/* Horizontal nav with items spread out */
.navbar {
  display: flex;
  justify-content: space-between;  /* horizontal distribution */
  align-items: center;             /* vertical alignment */
}

/* Equal-width columns that wrap on small screens */
.card-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.card { flex: 1 1 280px; }

Grid in Practice

/* Dashboard layout with named areas */
.dashboard {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 250px 1fr;
  grid-template-rows: 60px 1fr 40px;
}
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }

/* Auto-fill responsive gallery */
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
}

They Are Complementary

The page layout uses Grid; content inside each grid cell often uses Flex. Grid defines macro structure (sidebar, main, header). Flex aligns items within each section (nav links, card contents, form rows).

Quick Decision Guide

ScenarioUse
Navigation barFlexbox
Card row that wrapsFlexbox
Photo gallery (auto-fill)Grid
Page layout with sidebarGrid
Form with aligned labels/inputsGrid
Center one elementEither (Flex simpler)

More Learning Topics