BuildUtilities

CSS Layout: Flexbox & Grid

Flexbox vs Grid

Flexbox is one-dimensional (row or column) and ideal for distributing items along a single axis. Grid is two-dimensional (rows and columns) and suited for complex page layouts. Use both together for maximum flexibility.

Flexbox Essentials

.container {
  display: flex;
  flex-direction: row;       /* row | column */
  justify-content: center;   /* main axis alignment */
  align-items: center;       /* cross axis alignment */
  gap: 1rem;                 /* spacing between items */
  flex-wrap: wrap;           /* allow wrapping */
}

.item {
  flex: 1;                   /* grow to fill space */
  flex-shrink: 0;            /* prevent shrinking */
  flex-basis: 200px;         /* initial size */
}

Grid Essentials

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);  /* 3 equal columns */
  grid-template-rows: auto 1fr auto;      /* header, content, footer */
  gap: 1rem;
}

.item {
  grid-column: 1 / 3;       /* span columns 1-2 */
  grid-row: 2;               /* place in row 2 */
}

/* Responsive without media queries */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

When to Use Each

  • Flexbox: Navigation bars, toolbars, card rows, centering content, distributing space
  • Grid: Page layouts, dashboards, image galleries, form layouts, any 2D arrangement
  • Both: Grid for the overall layout, Flexbox for components within grid cells

Common Patterns

/* Holy Grail Layout (Grid) */
.page {
  display: grid;
  grid-template: "header header" auto
                 "sidebar main"  1fr
                 "footer footer" auto / 250px 1fr;
}

/* Centered card (Flexbox) */
.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

Experiment visually with our Flexbox Playground and CSS Grid Generator.

FAQ

Can I nest Flexbox inside Grid?

Yes, and it's recommended. Use Grid for macro layout and Flexbox for micro layout within grid cells.

Is Grid supported in all browsers?

CSS Grid has full support in all modern browsers (Chrome, Firefox, Safari, Edge). IE 11 has partial, outdated support.

Try These Tools

Related Documentation

Tip Jar