CSS Grid vs Flexbox

Introduction

Flexbox and Grid are the two core layout systems in modern CSS. Flexbox is one-dimensional (row OR column). Grid is two-dimensional (rows AND columns).

1. Flexbox Basics (1D Layout)

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
    

2. Grid Basics (2D Layout)

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: auto auto;
  gap: 10px;
}
    

3. When to Use Flexbox

Example:

.menu {
  display: flex;
  gap: 20px;
}
    

4. When to Use Grid

Example:

.dashboard {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;
}
    

5. Flexbox: Auto-Flowing Items

.flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
    

6. Grid: Explicit Track Control

.grid {
  display: grid;
  grid-template-columns: 150px 150px;
  grid-template-rows: 100px 100px;
}
    

7. Alignment Differences

Flexbox alignment:

justify-content: center;
align-items: center;
    

Grid alignment:

place-items: center;
place-content: space-between;
    

8. Overlap & Layering (Grid Only)

.item {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}
    

9. Flexbox vs Grid Summary Table

Flexbox:
- 1D layout (row OR column)
- Content-driven sizing
- Best for UI components

Grid:
- 2D layout (rows AND columns)
- Layout-driven sizing
- Best for whole page layouts
    

10. Combined Example

You can use BOTH together:

.page {
  display: grid;
  grid-template-columns: 200px 1fr;
}

.nav {
  display: flex;
  flex-direction: column;
}
    

Summary