CSS Grid vs Flexbox: When to Use Each One (With Real Examples)

The “Grid vs Flexbox” question has a boring but correct answer: use both, for different things. Here’s exactly what that means in practice.

The Core Difference

Flexbox is for laying out items in one direction – either a row or a column. CSS Grid is for laying out items in two dimensions simultaneously – rows and columns at the same time.

That’s it. That’s the deciding factor for 90% of layout decisions.

Use Flexbox For:

Navigation Bars

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

.nav-links {
  display: flex;
  gap: 1.5rem;
  list-style: none;
}

Centering Things

.centered-card {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

Components with Variable-Width Items

.button-group {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap; /* Wraps to next line when there's no space */
}

Use Grid For:

Page-Level Layouts

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

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

Card Grids

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

This creates a responsive grid that automatically adjusts columns – no media queries needed!

Complex Form Layouts

.form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group.full-width {
  grid-column: 1 / -1; /* Span all columns */
}

The Hybrid Approach

Most real layouts use both. Here’s a typical pattern:

/* Grid for overall layout */
.app {
  display: grid;
  grid-template-areas: "nav" "main" "footer";
  grid-template-rows: auto 1fr auto;
}

/* Flexbox for items within the nav */
nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* Grid for the main content area */
main {
  display: grid;
  grid-template-columns: 1fr 3fr;
  gap: 2rem;
}

/* Flexbox for items inside sidebar */
.sidebar-section {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

Practical Decision Making

When starting a new component, I ask: “Am I arranging things in a line, or am I creating a 2D structure?” Line → Flexbox. 2D structure → Grid.

Second question: “Do I want the content to determine the layout, or the layout to determine the content?” Content drives layout → Flexbox. Layout drives content placement → Grid.

These two questions get me to the right answer 90% of the time. The other 10% is experimentation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top