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;
}
- Best for navbars
- Horizontal or vertical alignment
- Content flows in one direction
2. Grid Basics (2D Layout)
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto auto;
gap: 10px;
}
- Best for full page layouts
- Controls rows + columns
- Precise placement
3. When to Use Flexbox
- Navbars
- Buttons in a row
- Centering things
- Vertical stacking
Example:
.menu {
display: flex;
gap: 20px;
}
4. When to Use Grid
- Dashboards
- Complex layouts
- Card grids
- Form layouts
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
- Use Flexbox for 1D alignment
- Use Grid for automated 2D layouts
- Grid is more structured, Flexbox is more dynamic
- Real projects usually mix both